首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么使用本机代码在java中实现反射?

为什么使用本机代码在java中实现反射?
EN

Stack Overflow用户
提问于 2022-04-05 05:16:37
回答 1查看 140关注 0票数 0

最近我正在阅读JDK 19( JDK 8,11,12反射代码似乎没有改变,所以任何版本都可以)有关反射的源代码。在reflection.cpp C++类Reflection::invoke_method方法中获得这样的类的关键是:

代码语言:javascript
复制
  oop mirror             = java_lang_reflect_Method::clazz(method_mirror);

获取这样的类实例:

代码语言:javascript
复制
InstanceKlass* klass = InstanceKlass::cast(java_lang_Class::as_Klass(mirror));

我发现本机代码通过使用JNI来调用java类来获取该类。为什么使用本机代码来实现反射?本机代码实现反射的优点是什么?我被谷歌搜索,发现没有人谈论这件事。

PS:我还读过由Java用bytecode实现的反射。

EN

回答 1

Stack Overflow用户

发布于 2022-04-05 06:24:27

实际上,JVM团队已经从ReflectionFactory.java中的注释中告诉了您答案,如下所示:

代码语言:javascript
复制
    //
    // "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

这就是为什么我们需要本土的反思。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71746628

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档