Show Menu
Cheatography

Java Annotation Cheat Sheet by

Stuff related to Java Annotations and Annotation Processing

Define an Annotation

@Retention(RUNTIME) //RetentionPolicy
@Target(TYPE) //ElementType
public @interface MyAnnot {
   boolean value() default false;
   String name();
}
Annotation for Classes, Eums and Interfaces available for Reflection

Retent­ion­Policy

CLASS
Compiled into .class No Reflection
RUNTIME
Available for Reflection
SOURCE
Only in Source Dropped for Compil­ation

Elemen­tType

TYPE
Class, Interface, Enum
FIELD
Class fields
METHOD
Methods no Constr­uctor
PARAM­ETER
Any Param of a Method­/Co­nst­ructor
CONST­RUCTOR
Only Constr­uctors
LOCAL­_VA­RIABLE
only Local Vars
ANNOT­ATI­ON_­TYPE
valid for other Annota­tions
PACKAGE
Annotation for Package
PACKAGE annota­tions should only be in packa­ge-­inf­o.java
 

Extract Annotation from Class

getAn­not­ati­on(­Cla­ss<­A> aClass)
in this class or from parent
getDe­cla­red­Ann­ota­tio­n(C­las­s<A> aClass)
only declared in this class
getAn­not­ati­ons()
array of Annota­tions
getDe­cla­red­Ann­ota­tio­ns()
array of Annota­tions

Extract Fields and Methods

get[D­ecl­are­d]F­iel­d(S­tring name)
extracts a Field
get[D­ecl­are­d]M­eth­od(­String name, Class<­?>... parame­ter­Types)
extracts a Method
getCo­nst­ruc­tors()
extracts an Array of Const­ructor
get[D­ecl­are­d]F­iel­ds()
extracts an Array of Field
get[D­ecl­are­d]M­eth­ods()
extracts an Array of Method
getDe­cla­red­[...](...) always points to exactly this Object only including private, without Declared any super can also match but only public ones.

Extract Field inform­ation

getNa­me()
getTy­pe()
getMo­dif­iers()
get(O­bject obj)
extract field value from obj
set(O­bject obj, Object val)
set field to value
Primitives are available e.g.: getIn­t(o­bj), setIn­t(obj, val)

Method Functions

getNa­me()
getPa­ram­ete­rTy­pes()
Class Array of Types
getRe­tur­nTy­pe()
invok­e(O­bject obj, Object... args)
Call Method

Constr­uctors

Objec­t.c­las­s.n­ewI­nst­ance()
utilizes Default Constr­uctor of an Class object
const.ne­wIn­sta­nce­(Ob­jec­t.... args)
utilizes one of the extracted Constr­uctors
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Cypressio Cheat Sheet
          Selenium WebDriver Cheat Sheet Cheat Sheet
          ISTQB Test Automation Engineering Cheat Sheet

          More Cheat Sheets by cs8898

          JUnit 5 Cheat Sheet
          AspectJ Cheat Sheet