Tuesday 13 October 2015

Obtain Constructors, Methods, Fields and Annotations using reflection

Constructors


Constructor[] constructors = MyClass.class.getConstructors();


Returns Constructor[] array of all public constructors of class or interface. An array of length 0 is returned if the class has no public constructors.


Constructor[]constructors = PrivateObject2.class.getDeclaredConstructors();


Returns Constructor[] array of all declared constructors. These are public, protected, default (package) access, and private constructors. The elements in the array returned are not in any particular order.

Fields
Returns Field[] array of all public accessible fields of class or interface.


Field[] method = MyClass.class.getFields();


Returns Field[] array of all public, protected, default (package) access, and private fields, but excludes inherited fields.


Field[] method = MyClass.class.getDeclaredFields();


Methods

To access the constructors of a class, we need to call getMethods method


Method[] method = MyClass.class.getMethods();

Method[] method = MyClass.class.getDeclaredMethods();


Annotations


Annotation[] annotations = MyClass.class.getAnnotations();

Annotation[] annotations = MyClass.class.getDeclaredAnnotations();

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...