I thought about a question before, whether it is possible to call a method in a class through a string. Baidu has been using the reflection mechanism for a long time to achieve the functions I want.
Let's take a look at the solution to my problem:
// 通过包名.类名得到Class对象
String info = "java.util.HashMap";
Class<?> demo = Class.forName(info);
// 通过demo对象获取实例
HashMap<String, String> hashMap = (HashMap<String, String>) demo.newInstance();
// 调用自带的put函数
hashMap.put("a", "1");
System.out.println("=========put函数调用后=========");
System.out.println(hashMap);
// 通过反射机制,得到remove方法
Method method = demo.getDeclaredMethod("remove", Class.forName("java.lang.Object"));
// 调用remove方法
method.invoke(hashMap, "a");
System.out.println("=========通过反射remove函数调用后=========");
System.out.println(hashMap);
Program running results:
=========put函数调用后=========
{a=1}
=========通过反射remove函数调用后=========
{}
We understand what Java's reflection mechanism can do.
Get method name
String info = "java.util.HashMap";
Class<?> demo = Class.forName(info);
Method[] methods = demo.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method);
}
Program running results:
public java.lang.Object java.util.HashMap.remove(java.lang.Object)
public boolean java.util.HashMap.remove(java.lang.Object,java.lang.Object)
public java.lang.Object java.util.HashMap.get(java.lang.Object)
......
Get attributes
String info = "java.util.HashMap";
Class<?> demo = Class.forName(info);
Field[] fields = demo.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
}
Program running results:
private static final long java.util.HashMap.serialVersionUID
static final int java.util.HashMap.DEFAULT_INITIAL_CAPACITY
static final int java.util.HashMap.MAXIMUM_CAPACITY
......
Get the parent class
String info = "java.util.HashMap";
Class<?> demo = Class.forName(info);
System.out.println(demo.getSuperclass());
Program running results:
class java.util.AbstractMap
Call class constructor
String info = "java.util.HashMap";
Class<?> demo = Class.forName(info);
// 通过demo对象获取实例
HashMap<String, String> hashMap = (HashMap<String, String>) demo.newInstance();
newInstance() is to call the constructor, and the no-argument constructor is called. If you need to carry parameters, just add it directly.
Now think about it, many J2EE frameworks that rely on xml may use the reflection mechanism.