Java Reflection: class “Method” to inovoke methods and get metadata

Java Logo

using java.lang.reflect.Method  you can get metadata/signature of methods (including private) and can invoke accessible methods at runtime.

Class Method provides a great tool to list all methods and find information about methods.  following tutorial will provide you more detail of class Method and invoking a method at runtime.

Getting List of Method Objects

 

Getting information/metadata about methods

Expand following code snippet.

Following code  will print whole method signature. Alternatively you can use specific method to get parameters, returnType and exceptions.

 

 getting a Method object

 

Invoking methods at Runtime

public Object invoke(Object obj, Object… args) throws IllegalAccessException, IllegalArgumentException,InvocationTargetException

Method invoke take variable length parameter, so you need to provide parameter type and number of parameter as calling method.

If method is static just pass null in place of classObject

 

Ways of loading class at run time and invoking method at run time

 

Another way to load class at run time and call method

Not sure what exactly the difference between these two ways of invoking method.  In both way  loading of class happening at runtime. In 1st way invoke is being used while in second ways object.method is being used.

 

Leave a Reply

Your email address will not be published. Required fields are marked *