public class Main {
public static void main(String[] args) throws Exception{
a();
b();
}
public static void a() throws Exception{
Properties properties = new Properties();
properties.load(new FileInputStream("src\\fanshe_lei\\re.properties"));
String class_ = properties.get("class").toString();
String methodname = properties.get("fangfa").toString();
Class cls = Class.forName(class_);
Object obj = cls.getDeclaredConstructor().newInstance();
Method method = cls.getMethod(methodname);
long a = System.currentTimeMillis();
for (int i=0;i<1000;i++){
method.invoke(obj);
}
long b = System.currentTimeMillis();
System.out.println(b-a);
}
public static void b(){
Dog dog = new Dog();
long a = System.currentTimeMillis();
for (int i=0;i<1000;i++){
dog.hi1();
}
long b = System.currentTimeMillis();
System.out.println(b-a);
}
}
运行结果
原因:
Method、Field、Constructor对象都有一个setAccessible()方法
该方法是启动或禁止访问安全检查的开关
优化:
将检测关闭
public static void c() throws Exception{
Properties properties = new Properties();
properties.load(new FileInputStream("src\\fanshe_lei\\re.properties"));
String class_ = properties.get("class").toString();
String methodname = properties.get("fangfa").toString();
Class cls = Class.forName(class_);
Object obj = cls.getDeclaredConstructor().newInstance();
Method method = cls.getMethod(methodname);
//===================================
// 关闭检测
method.setAccessible(true);
//===================================
long a = System.currentTimeMillis();
for (int i=0;i<100000000;i++){
method.invoke(obj);
}
long b = System.currentTimeMillis();
System.out.println(b-a);
}
}