环境准备
package com.lilei.pack09; public class Logger { public void show(){ System.out.println("hello world"); } public int cal(int a,int b){ return a + b; } public String multi(String... args){ return args.length+";"; } }
使用反射
package com.lilei.pack09; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class app1 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class c = Class.forName("com.lilei.pack09.Logger"); Method[] ms = c.getMethods(); Method m_show = c.getMethod("show", null); m_show.invoke(new Logger(), null); Method m_cal = c.getMethod("cal", new Class[]{int.class,int.class}); Object result = m_cal.invoke(new Logger(), 233,2233); new Logger().multi("v","dd","ds"); System.out.println(result); Method m_multi = c.getMethod("multi", new Class[]{String[].class}); result = m_multi.invoke(new Logger(), new Object[]{new String[]{"v","dd","ds"}}); System.out.println(result); } }
性能比较
常规创建对象调用方法和通过反射进行调用方法
package com.lilei.pack09; import java.util.Date; public class app2 { public static void main(String[] args) { Logger logger = new Logger(); int result = 0; System.out.println(new Date()); for (int i = 0; i < 2000000000; i++){ result += logger.cal(i,i); } System.out.println(result); System.out.println(new Date()); } }
消耗时间:
package com.lilei.pack09; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; public class app3 { public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Logger logger = new Logger(); Method m = logger.getClass().getMethod("cal", new Class[]{int.class,int.class}); int result = 0; System.out.println(new Date()); for (int i = 0; i < 2000000000; i++){ Integer in = (Integer)m.invoke(logger, i,i); result += in.intValue(); } System.out.println(result); System.out.println(new Date()); } }
消耗时间:
通过使用反射消耗的时间是通过对象调用方法的40-50倍