ReflectUtil
Introduction
Java’s reflection mechanism can make the language more flexible and the operations on objects more “dynamic”. Therefore, in some cases, reflection can achieve better results with less effort. Hutool has made tool-based encapsulation for Java’s reflection mechanism, including:
- Obtaining constructors
- Obtaining fields
- Obtaining field values
- Obtaining methods
- Executing methods (object methods and static methods)
Usage
Getting all methods of a class
Method[] methods = ReflectUtil.getMethods(ExamInfoDict.class);
Getting a specified method of a class
Method method = ReflectUtil.getMethod(ExamInfoDict.class, "getId");
Creating an object
ReflectUtil.newInstance(ExamInfoDict.class);
Executing a method
class TestClass {
private int a;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
TestClass testClass = new TestClass();
ReflectUtil.invoke(testClass, "setA", 10);