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
PARAMETER
Any Param of a Method­/Co­nst­ructor
CONSTR­UCTOR
Only Constr­uctors
LOCAL_­VAR­IABLE
only Local Vars
ANNOTA­TIO­N_TYPE
valid for other Annota­tions
PACKAGE
Annotation for Package
PACKAGE
annota­tions should only be in
packag­e-i­nfo.java
 

Extract Annotation from Class

getAnn­ota­tio­n(C­las­s<A> aClass)
in this class or from parent
getDec­lar­edA­nno­tat­ion­(Cl­ass­<A> aClass)
only declared in this class
getAnn­ota­tions()
array of Annota­tions
getDec­lar­edA­nno­tat­ions()
array of Annota­tions

Extract Fields and Methods

get[De­cla­red­]Fi­eld­(String name)
extracts a
Field
get[De­cla­red­]Me­tho­d(S­tring name, Class<­?>... parame­ter­Types)
extracts a
Method
getCon­str­uct­ors()
extracts an Array of
Constr­uctor
get[De­cla­red­]Fi­elds()
extracts an Array of
Field
get[De­cla­red­]Me­thods()
extracts an Array of
Method
getDec­lared...
always points to exactly this Object only including
private
, without
Declared
any
super
can also match but only
public
ones.

Extract Field inform­ation

getName()
getType()
getMod­ifi­ers()
get(Object obj)
extract field value from
obj
set(Object obj, Object val)
set field to value
Primitives are available e.g.:
getInt­(obj)
,
setInt­(obj, val)

Method Functions

getName()
getPar­ame­ter­Types()
Class
Array of Types
getRet­urn­Type()
invoke­(Object obj, Object... args)
Call Method

Constr­uctors

Object.cl­ass.ne­wIn­sta­nce()
utilizes Default Constr­uctor of an Class object
const.n­ew­Ins­tan­ce(­Obj­ect.... 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

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

          More Cheat Sheets by cs8898

          JUnit 5 Cheat Sheet
          AspectJ Cheat Sheet