When I tested the difference between Class.forName and using Class as a method parameter to reflect, I found a problem. there is my codes:
public class AppleTest {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, ClassNotFoundException {
testClass(TestEntity.class);
testClassForName("com.example.demo.enumtest.TestEntity");
}
public static void testClass(Class traget) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
long begin = System.currentTimeMillis() ;
Method method = traget.getMethod("setId", Integer.TYPE);
for (int i = 0; i < 100000000; i++) {
method.invoke(traget.newInstance(), i);
}
long time = System.currentTimeMillis() - begin;
System.out.println("Class:" + String.valueOf(time) + "ms");
}
public static void testClassForName(String className) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException, ClassNotFoundException {
long begin = System.currentTimeMillis();
Class traget = Class.forName(className);
Method method = traget.getMethod("setId", Integer.TYPE);
for (int i = 0; i < 100000000; i++) {
method.invoke(traget.newInstance(), i);
}
long time = System.currentTimeMillis() - begin;
System.out.println("classForName:" + String.valueOf(time) + "ms");
}
and the result was:
Class:703ms
classForName:563ms
I was surprised why use Class.forName takes less time, so I changed their position in the main function to see what will happen,and the result has changed too:
classForName:687ms
Class:547ms
So I want to ask that Is the JDK cache the reflection object by default? and How to write efficient reflection code