Home > Software design >  why using native code to implement reflection in java
why using native code to implement reflection in java

Time:04-05

Recently I am reading the JDK 19(the JDK 8,11,12 the reflection code seems did not change, so any version is ok) source code about reflection. The key to get class like this in reflection.cpp C class Reflection::invoke_method method:

  oop mirror             = java_lang_reflect_Method::clazz(method_mirror);

get the class instance like this:

InstanceKlass* klass = InstanceKlass::cast(java_lang_Class::as_Klass(mirror));

I found the native code invoke the java class by using JNI to get the class. why using native code to implement the reflection? what is the advantage of native code to implement reflection? I am googled and found no one talk about this.

PS: I have also read the reflection could implement by Java with bytecode.

CodePudding user response:

Actually the JVM team have already tell you the answer, from the comment in ReflectionFactory.java, the comment like this:

    //
    // "Inflation" mechanism. Loading bytecodes to implement
    // Method.invoke() and Constructor.newInstance() currently costs
    // 3-4x more than an invocation via native code for the first
    // invocation (though subsequent invocations have been benchmarked
    // to be over 20x faster). Unfortunately this cost increases
    // startup time for certain applications that use reflection
    // intensively (but only once per class) to bootstrap themselves.
    // To avoid this penalty we reuse the existing JVM entry points
    // for the first few invocations of Methods and Constructors and
    // then switch to the bytecode-based implementations.
    //
    // Package-private to be accessible to NativeMethodAccessorImpl
    // and NativeConstructorAccessorImpl

that's why we need native reflection.

  • Related