Tuesday, April 19, 2011

Java Reflections


Java Reflections is one of the most powerful API in Java. Java Reflection API allows us to access metadata about the classes at runtime i.e. Reflections allows us to find out constructors, fields and methods from a Java class.
In this post I will show how to find out constructors, fields and methods from a Java class.

Constructors
Following code shows how to find out constructors from a class

Constructor constructors[]=java.lang.String.class.getDeclaredConstructors();
// getDeclaredConstructors() returns all the constructors which are defined in this class including private.
// it will not return constructors from base class.

Constructor constructors[]=java.lang.String.class.getConstructors();
// getConstructors() returns all the constructors including constructors from base class also, although this will
// not return any private or protected constructors.


for(Constructor cc:constructors){
System.out.println(cc);
}

Methods
Following code shows how to find out methods from a class

Method methods[]=java.lang.String.class.getDeclaredMethods();
// same as constructors getDeclaredMethods() returns all the methods from a class including private.
// it will not return methods from base class.

Method methods[]=java.lang.String.class.getMethods[];
// getMethods() will return public methods from this class and base class.


for(Method method:methods){
System.out.println(
}

Fields
Following code shows how to find out fields from a class

Field fields[]=java.lang.String.class.getDeclaredFields();
// same as above getDeclaredFields returns all methods(public, private and protected) from this class only.

Field fields[]=java.lang.String.class.getFields();
// getFields will return public fields from this and base class.

With these following are the methods which returns exact constructor, field and method, we need to pass parameter types to get exact respective element.

// getConstructor
Constructor c=java.lang.String.class.getConstructor(new Class[]{String.class});

// getMethod
Method method=java.lang.String.class.getMethod("equals", new Class[]{String.class});

// getField
Field field=SomeClass.class.getField("nameOfField");

No comments:

Post a Comment

Ads Inside Post