Java method reflection
In this chapter you will learn:
- Using java.lang.reflect.Method to do method reflection
- Find out Method's return type, modifiers and parameters
- How to invoke a method
Method Reflection with java.lang.reflect.Method
A Method provides information about a method on a class or interface.
The following code demonstrates Method's invoke(Object, Object...)
method.
import java.lang.reflect.Method;
//from j a v a 2 s . com
class X {
public void objectMethod(String arg) {
System.out.println("Instance method: " + arg);
}
public static void classMethod() {
System.out.println("Class method");
}
}
public class Main {
public static void main(String[] args) {
try {
Class<?> clazz = Class.forName("X");
X x = (X) clazz.newInstance();
Class[] argTypes = { String.class };
Method method = clazz.getMethod("objectMethod", argTypes);
Object[] data = { "Hello" };
method.invoke(x, data); // Output: Instance method: Hello
method = clazz.getMethod("classMethod", (Class<?>[]) null);
method.invoke(null, (Object[]) null); // Output: Class method
} catch (Exception e) {
System.err.println(e);
}
}
}
Method's return type, modifiers and parameters
With java.lang.reflect.Method
we can get Method's return type, modifiers and parameters
The following code uses reflection to print out methods' signature for a given class.
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/*j a va2 s . c o m*/
public class Main{
public static void main(String[] args) {
Method[] methods = java.lang.Integer.class.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
Class retType = m.getReturnType();
Class[] paramTypes = m.getParameterTypes();
String name = m.getName();
System.out.print(Modifier.toString(m.getModifiers()));
System.out.print(" " + retType.getName() + " " + name + "(");
for (int j = 0; j < paramTypes.length; j++) {
if (j > 0)
System.out.print(", ");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
}
The output:
Invoke a method
We can invoke a method with reflection and pass in values for parameters.
import java.lang.reflect.Method;
//from j a v a2 s.co m
public class Main {
public static void main(String[] a) throws Exception {
Method f = Math.class.getMethod("sqrt", new Class[] { double.class });
try {
Object[] args = { new Double(10) };
Double d = (Double) f.invoke(null, args);
double y = d.doubleValue();
System.out.println(y);
} catch (Exception e) {
System.out.println(e);
}
}
}
The output:
Next chapter...
What you will learn in the next chapter: