如何获取所有“参与”的班级在给定的对象中?

发布于 2024-12-13 09:15:09 字数 445 浏览 3 评论 0原文

我有一个 java 对象,一个 Object 类的实例 - 这就是我所知道的。现在我需要创建一个参与其创建的Class-es列表,包括它自己的类、所有父类、其属性和方法的所有类。例如:

List obj = new ArrayList();
obj.add(new Integer(4));
obj.add(new Foo());
System.out.println(allRelatedClasses(obj));

应该输出这样的内容:

Object, List, Collection, Iterable, Serializable, Cloneable, RandomAccess, 
ArrayList, Integer, Foo

Is it possible at all?

I have a java object, an instance of class Object - that's all I know about it. Now I need to create a list of Class-es that took participation in its creation, including its own class, all parent classes, all classes of its properties and methods. For example:

List obj = new ArrayList();
obj.add(new Integer(4));
obj.add(new Foo());
System.out.println(allRelatedClasses(obj));

Should output something like this:

Object, List, Collection, Iterable, Serializable, Cloneable, RandomAccess, 
ArrayList, Integer, Foo

Is it possible at all?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空名 2024-12-20 09:15:09

Reflections 库可以处理相当多的问题。

就“参与其创建的内容”而言,您需要将其从字节码中提取出来。有几个库可以帮助解决这个问题,例如 ASM 和 BCEL。如果您只需要所有依赖项,DepFind可能就足够了。

如果您需要将自己限制在您所说的“创建过程中涉及的内容”,那么您只需要 ctor 中涉及的类以及该 ctor 调用的方法。

然而,如果一个类使用任何反射,那么所有的赌注都将落空——这些类型的依赖关系很难追踪,并且很难/不可能识别实际使用了什么。

The Reflections library can handle quite a bit of that.

In terms of "what took part in its creation", you'll need to pull that out of the bytecode. There are several libraries that can help with this, like ASM and BCEL. If you just need all dependencies, DepFind might be enough.

If you need to limit yourself to what you said, "what's involved in its creation", then you'd only want the classes involved in the ctor and methods the ctor calls.

If a class uses any reflection, however, all bets are off--those types of dependencies are difficult to track down, and it's difficult/impossible to identify what's actually used.

我是有多爱你 2024-12-20 09:15:09

当然,您可以使用反射来做到这一点。 obj.getClass() 返回您自己的类,obj.getClass().getParent() 返回其父类。然后你可以循环调用getParent(),直到到达Object

接口、字段、方法、注释也是如此。只是不要忘记,您应该调用 getDeclaredMethods()getDeclaredFields() 来获取所有方法和字段,包括私有方法和字段。并且您必须调用setAccessible(true)来处理私有成员。

1小时的工作,你就完成了。去!祝你好运。

Sure, you can do it using reflection. obj.getClass() returns your own class, obj.getClass().getParent() returns its parent. Then you can call getParent() in loop until you arrive to Object.

The same is with interfaces, fields, methods, annotations. Just do not forget that you should call getDeclaredMethods() and getDeclaredFields() to get all methods and fields including private. And you have to call setAccessible(true) to deal with private members.

1 hour of work and you are done. Go! Good luck.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文