一 代码
package com.cakin.javademo;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @ClassName: Reflection
* @Description: 反射性能测试
* @Date: 2020/8/15
* @Author: cakin
*/
public class Reflection {
public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
test1();
test2();
test3();
}
// 普通方式
public static void test1() {
Dog1 dog = new Dog1();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
dog.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方式调用时间:" + (endTime - startTime));
}
// 反射方式——不关闭检测
public static void test2() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Dog1 dog = new Dog1();
Class dogClass = dog.getClass();
Method method = dogClass.getDeclaredMethod("getName");
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
method.invoke(dog, null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射方式——不关闭检测调用时间:" + (endTime - startTime));
}
// 反射方式——关闭检测
public static void test3() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Dog1 dog = new Dog1();
Class dogClass = dog.getClass();
Method method = dogClass.getDeclaredMethod("getName");
method.setAccessible(true);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
method.invoke(dog, null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射方式——关闭检测调用时间:" + (endTime - startTime));
}
}
class Dog1 {
private String name;
public Dog1() {
}
public Dog1(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
二 测试结果
普通方式调用时间:3
反射方式——不关闭检测调用时间:3539
反射方式——关闭检测调用时间:1858
三 说明
普通方式调用最快。
反射的不关闭检测方式调用很慢。
能不用反射尽量不用反射。