Java反射API中的反射方法是什么?
除了Java反射API之外,我们还可以使用什么方法呢?我们如何定义它?源代码示例会很有帮助。
What is the method that we can use instead of the Java reflection API? How can we define it? A source code example will be helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JDK 1.6 具有动态编译 Java 类的能力(请参阅 getSystemJavaCompiler )。如果您不想使用反射(出于性能原因,我们使用动态编译),那么这是一个合理的方法。
从包含代码的字符串创建 Java 源文件:
然后动态加载新创建的类文件。
或者,使用字节码操作(例如 ASM)动态创建类。
这两种方法都比标准反射复杂得多,但与反射相比可以显着提高性能。
JDK 1.6 has the ability to dynamically compile Java classes (see getSystemJavaCompiler). If you don't want to use reflection (we're using dynamic compilation for performance reasons) then this is a reasonable approach.
Create a Java source file from a string containing the code:
Then you load the newly created class files dynamically.
Alternatively, use byte code manipulation (such as ASM) to create classes on the fly.
Both of these methods are a good deal more complex than standard reflection, but can have significant performance improvements over reflection.
通常,当您使用Reflection API时,这是因为您需要动态访问类的内容,并且没有其他方法可以做到这一点。如果您想要更详细的答案,请添加更多详细信息(您到底想实现什么目标?):)
Usually when you use the Reflection API, that's because you need to dynamically access the content of a class, and there is no other way to do it. Please add more details (what exactly are you trying to achieve?) if you want a more detailled answer :)