Java 反射:如何检索匿名内部类?
我在另一个类中有一个匿名内部类(SomeClass
)。
SomeClass.class.getClasses()
和 SomeClass.class.getDeclaredClasses()
都返回空数组。
我在Class
' Javadocs 中找不到关于此的一些提示。
可以通过某种方式使用反射来检索匿名内部类吗?
匿名内部类和普通内部类之间还有哪些显着差异?
I have an anonymous inner class inside another class (SomeClass
).
Both SomeClass.class.getClasses()
and SomeClass.class.getDeclaredClasses()
return empty arrays.
I couldn't find some hints on this in Class
' Javadocs.
Can anonymous inner classes be retrieved using reflection in some way?
What else are notable differences between anonymous inner classes and normal inner classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试对 Class$1 ... Class$n 进行强力搜索,直到找不到更多为止。
You could try a brute force search of Class$1 ... Class$n until you can't find any more.
如果它使用反射,这可能是一个非常糟糕的主意。抛开这一点,我相信您可以在运行时添加额外的内部类,因此列出可能尚未想到的类是没有意义的。我想,列出当前加载的类需要通过 Java 代理或类似代理。
匿名内部类由名称、封闭方法和附加合成字段组成,用于复制已复制的外部局部变量。一个类在运行时与另一个类几乎相同。请记住,1.1 引入了内部类,但自 1.0 以来类文件几乎没有变化。
If it's using reflection, it's probably a really bad idea. Leaving that aside, I believe you can additional inner classes at runtime, so it doesn't make sense to list classes that may not have been thought of yet. Listing currently loaded classes would, I guess, require going through Java agents or similar.
Anonymous inner classes have made up names, an enclosing method and additional synthetic fields for copying external local variables that have been copied. One class is pretty much the same as another at runtime. Remember that 1.1 introduced inner classes, but class files have barely changed since 1.0.