最近我正在阅读JDK 19( JDK 8,11,12反射代码似乎没有改变,所以任何版本都可以)有关反射的源代码。在reflection.cpp C++类Reflection::invoke_method方法中获得这样的类的关键是:
oop mirror = java_lang_reflect_Method::clazz(method_mirror);获取这样的类实例:
InstanceKlass* klass = InstanceKlass::cast(java_lang_Class::as_Klass(mirror));我发现本机代码通过使用JNI来调用java类来获取该类。为什么使用本机代码来实现反射?本机代码实现反射的优点是什么?我被谷歌搜索,发现没有人谈论这件事。
PS:我还读过由Java用bytecode实现的反射。
发布于 2022-04-05 06:24:27
实际上,JVM团队已经从ReflectionFactory.java中的注释中告诉了您答案,如下所示:
//
// "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这就是为什么我们需要本土的反思。
https://stackoverflow.com/questions/71746628
复制相似问题