2

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

Radiodef
  • 37,180
  • 14
  • 90
  • 125
JunRzz
  • 107
  • 3
  • 13
  • 3
    See: https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – Jacob G. Jun 26 '18 at 02:34
  • 2
    These timings are probably just due to class loading and warmup effects. Whichever is run first takes longer. See Jacob's link for more info about this. – Radiodef Jun 26 '18 at 02:39
  • think you,I use the JMH to test,and the result was right,Sure enough, using class.forName is slower – JunRzz Jun 26 '18 at 03:39

0 Answers0