Java Reflection (part of the java.lang.reflect package and java.lang.Class package) provides the ability to inspect and modify the run-time behavior of applications. It is a very powerful and useful technique.
Using this technique, a class or an interface can be inspected. The fields, constructors, and methods can be retrieved at run-time.
Moreover, it can be used to load a class dynamically, instantiate the class, invoke its methods, and change the values of fields.
Let us start with an example, as follow. In this example, we are trying to load the MySQL Driver class at run-time. The driver class is available in the MySQL connector jar.
In this tutorial, sample codes are developed using Eclipse IDE. Hence, you can download the codes, import them into Eclipse IDE and test them.
You may try the following code.
Using this technique, a class or an interface can be inspected. The fields, constructors, and methods can be retrieved at run-time.
Moreover, it can be used to load a class dynamically, instantiate the class, invoke its methods, and change the values of fields.
Let us start with an example, as follow. In this example, we are trying to load the MySQL Driver class at run-time. The driver class is available in the MySQL connector jar.
In this tutorial, sample codes are developed using Eclipse IDE. Hence, you can download the codes, import them into Eclipse IDE and test them.
You may try the following code.
package com.t4b.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
public class TestMain {
static Class<?> c;
public static void main(String[] args) {
try {
c = Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(c.getName());
System.out.println(c.getCanonicalName());
System.out.println(c.getModifiers());
System.out.println(c.getSimpleName());
System.out.println(c.isLocalClass());
System.out.println(c.isMemberClass());
System.out.println(c.isSynthetic());
System.out.println(c.getSuperclass());
System.out.println(c.getSuperclass().getSuperclass());
System.out.println("Methods:");
for (Method m : c.getMethods()) {
System.out.println("Method: " + m);
System.out.println(" Return Type: " + m.getReturnType());
for (Type t : m.getParameterTypes())
System.out.println(" Arguments: " + t.toString());
}
System.out.println("Constructors:");
for (Constructor<?> cons : c.getConstructors()) {
System.out.println("Constructor: " + cons);
for (Type t : cons.getParameterTypes())
System.out.println(" Arguments: " + t.toString());
}
System.out.println("Fields:");
for (Field field : c.getDeclaredFields()) {
System.out.println(field.getName());
System.out.println(field.getType());
}
System.out.println("Interfaces:");
for (Class<?> cls : c.getInterfaces()) {
System.out.println(cls.getName());
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.