java反射很慢吗?
import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import org.apache.commons.lang.time.StopWatch;/* * @Description * * @CreateDate 2011-9-15 * * @Author <a href="mailto:bohr.qiu@gmail.com">Bohr.Qiu</a> */public class PerformaceTest {public int test() {int sum = 0;for (int i = 0; i < 10000; i++) {sum += i;}return sum;}public Method test1(){PerformaceTest test1 = new PerformaceTest();Method method=null;try {for (int i = 0; i < 10000; i++) { method = test1.getClass().getDeclaredMethod("test");}} catch (SecurityException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();}return method;}/** * @param args * @throws NoSuchMethodException * @throws SecurityException * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */public static void main(String[] args) throws SecurityException,NoSuchMethodException, IllegalArgumentException,IllegalAccessException, InvocationTargetException {PerformaceTest test = new PerformaceTest();StopWatch sw = new StopWatch();sw.start();int times = 500000;//测试直接调用for (int i = 0; i < times; i++) {test.test();}sw.stop();System.out.println("direct:" + sw.toString());Method method = test.getClass().getDeclaredMethod("test");sw.reset();sw.start();//测试反射调用for (int i = 0; i < times; i++) {method.invoke(test);}sw.stop();System.out.println("reflect:" + sw.toString());sw.reset();sw.start();//测试直接调用for (int i = 0; i < times; i++) {test.test();}sw.stop();System.out.println("direct" + sw.toString());sw.reset();sw.start();//测试反射调用for (int i = 0; i < times; i++) {method.invoke(test);}sw.stop();System.out.println("reflect:" + sw.toString());sw.reset();sw.start();times=times/1000;//测试反射类探测,测试测试减少为1000倍for (int i = 0; i < times; i++) {test.test1();}sw.stop();System.out.println("getreflect:" + sw.toString());}}