Monday, 25 April 2016

How to inspect constructors, fields and methods using Reflection ?


Inspecting Constructors

Instantiating Objects using Constructor Object
// Get constructor that takes a String as argument
Constructor constructor 
        MyObject.class.getConstructor(String.class);
MyObject myObject = 
       (MyObject) constructor.newInstance("constructor-arg1");

Get parameter types of constructor
Class[] parameterTypes = constructor.getParameterTypes();


Inspecting fields
If you know the name of the field you want to access, you can access it like this :
Field field = aClass.getField("someField");
If no field exists with the name given as parameter to the getField() method, a NoSuchFieldException is thrown.

Get field name and type
String fieldName = field.getName();
Object fieldType = field.getType();

Get and set values using the field.get() and field.set() methods
Object value = field.get(objectInstance);
field.set(objetInstance, value);


Inspecting methods
Return the public method named "doSomething", in the given class which takes a String as parameter
Method method 
         aClass.getMethod("doSomething", new Class[]{String.class});
If no method matches the given method name and arguments, in this case String.class, a NoSuchMethodException is thrown.

If the method you are trying to access takes no parameters, pass null as the parameter type array :
Method method = aClass.getMethod("doSomething", null);

Get parameter types and return types
Class[] parameterTypes = method.getParameterTypes();
Class returnType = method.getReturnType();

Invoking method
Object returnValue = method.invoke(null, "parameter-value1");
If the method is static you supply null instead of an object instance.

If method is not static, you need to supply a valid instance on which you like to invoke it.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.