由于 Java 反射是要解析字节码,将内存中的对象进行解析,包括了一些动态类型,而 JVM 无法对这些代码进行优化。因此,反射操作的效率要比那些非反射操作低得多!
import java.lang.reflect.Method;public class Test2 {public static void main(String[] args) {try {//反射耗时Class clazz = Class.forName("Reflict.Users");Users users = (Users) clazz.newInstance();long reflectStart = System.currentTimeMillis();Method method = clazz.getMethod("setUserage", int.class);for(int i=0;i<100000000;i++){method.invoke(users,25);}long reflectEnd = System.currentTimeMillis();//非反射方式的耗时long start = System.currentTimeMillis();Users u = new Users();for(int i=0;i<100000000;i++){u.setUserage(25);}long end = System.currentTimeMillis();System.out.println("反射执行时间:"+(reflectStart-reflectEnd));System.out.println("非反射执行时间:"+(start-end));} catch (Exception e) {e.printStackTrace();}}}

