getDeclaredMethod方法返回的Method对象其实都是一个新的对象,且新对象的root属性都指向原来的Method对象,如果需要频繁调用,最好把Method对象缓存起来。
测试用例
/**
* @Desc:
* @Author: heling
* @Date: 2020/9/2 9:29
*/
public class Test {
public static Map<String, Method> map = new HashMap();
public static void main(String[] args) throws NoSuchMethodException {
Class<TaskBase> clazz = TaskBase.class;
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
if (null == map.get("getDeleteFlag")) {
map.put("getDeleteFlag",clazz.getDeclaredMethod("getDeleteFlag"));
}
}
System.out.println(System.currentTimeMillis()- start);
long start2 = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
Method method = clazz.getDeclaredMethod("getDeleteFlag");
}
System.out.println(System.currentTimeMillis()- start2);
}
}
测试结果
8
62