可以“探索”吗?哪些对象在运行时通过反射在另一个对象中定义? [英] Is it possible to "explore" which objects are defined within an other object via reflection at runtime?

查看:145
本文介绍了可以“探索”吗?哪些对象在运行时通过反射在另一个对象中定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

object A {
  object AA extends A
  object AB extends A
  object AC extends A
}; class A

如何看到对象中定义的对象?运行时
我认为对象A 中的方法带有一些简单的反射代码就足够了,但似乎编译器在编译时展平了对象层次结构并创建了以下内容类文件:

How is it possible to "see" the objects defined within object A at runtime? I thought a method within object A with some simple reflection code would be enough, but it seems that the compiler flattens the object hierarchy at compile time and created the following class files:


  • A.class - A类

  • A $ class - A的同伴对象

  • A $ AA $。 class - AA对象

  • A $ AB $ .class - AB对象

  • A $ AC $ .class - AC对象

  • A.class – The class A
  • A$class – The companion object of A
  • A$AA$.class – The AA object
  • A$AB$.class – The AB object
  • A$AC$.class – The AC object

编译后没有关于 AA AB AC 在伴侣对象 A 中,这将有我的 magicMethod

After compilation there is no sign about AA, AB or AC in the companion object A, which would have my magicMethod.

似乎 ClassLoader 类有一些与我打算做的相关的方法,但似乎所有人都希望得到类的确切String名称。有没有办法让ClassLoader找到所有类文件,从该类的路径中调用此方法的类( A $ )开始?

It seems that the ClassLoader class has some related methods to what I plan to do, but all seem to expect the exact String name of the class. Is there a way to ask the ClassLoader to find all class files starting with the class from which this method is called (A$) in the path of that class?

推荐答案

代码 this.getClass.getDeclaredClasses 应该返回所请求的信息。

但是在尝试使用各种工具之后,它怀疑某些东西在这里没有正常工作。

But after experimenting a bit with various tools, it suspect that something is not working correctly here.

我在Scala中尝试了各种类,而不是对象和Java源代码,并从行为判断它应该清楚地返回预期结果,但目前它没有。

I tried various things in Scala with classes inside classes instead of objects and Java sources and judging from the behaviour it should clearly return the expected results but currently it doesn't.

要么我从根本上错了,要么 scalac 可能忘记将一些元数据放入它生成的类文件中,从而导致错误的反映信息。

Either I'm fundamentally wrong or scalac might be forgetting to put some bits of metadata into the class files it generates, resulting in incorrect reflection information.

请参阅这bug re端口

这篇关于可以“探索”吗?哪些对象在运行时通过反射在另一个对象中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆