是否有一个库可以为我提供另一个类中出现的类的所有实例?
我有一个类,它有几个字段,它们是另一个类的子类。我想快速找到顶级类中该子类的所有实例。
例如,
public class TopClass {
private ClassIWant1 myVar1;
private ClassIWant2 myVar2;
private OtherJunk myVar3;
private Nested myVar4;
}
public class Nested {
private ClassIWant3 myVar11;
}
public class SuperClass {
}
public ClassIWant1 extends SuperClass {}
public ClassIWant2 extends SuperClass {}
public ClassIWant3 extends ClassIWant1 {}
如果我要使用 TopClass
实例运行该示例,我希望获得一个包含 myVar1、myVar2 和 myVar11 值的列表。
我对如何使用反射手动执行此操作有一个大致的了解,但我希望我不必重新发明轮子。有图书馆可以做到这一点吗?
我熟悉 ReflectUtils,但我不确定它是否可以做到这一点。
I have a class which has several fields which are a subclass of another class. I want to quickly find all instances of that subclass within the top level class.
For example
public class TopClass {
private ClassIWant1 myVar1;
private ClassIWant2 myVar2;
private OtherJunk myVar3;
private Nested myVar4;
}
public class Nested {
private ClassIWant3 myVar11;
}
public class SuperClass {
}
public ClassIWant1 extends SuperClass {}
public ClassIWant2 extends SuperClass {}
public ClassIWant3 extends ClassIWant1 {}
If I were to run that example through with an instance of TopClass
I would expect to get a List containing the values for myVar1, myVar2, and myVar11.
I have a general idea of how to use reflection to do this manually, but I'm hoping that I don't have to reinvent the wheel. Is there a library that can do this?
I am familiar with ReflectUtils, but I am not sure if that can do this or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我正确理解您的请求,您正在寻找类似的内容:
这通过使用声明的字段的静态类型来工作。也就是说,如果您将一个字段声明为
Object
,但它包含SuperClass
或其后代之一的实例,则不会找到该字段。如果字段将其设置为值,它也会返回 null。我不知道这会对原始类型产生什么影响。免责声明:代码已在一个乐观的示例上进行了简要测试,如果它导致您的计算机着火,我不承担任何责任。
If I understand your request correctly, you're looking for something like this:
This works by using the static types of the fields as declared. That is, if you declare a field as
Object
but it holds an instance ofSuperClass
or one of its descendants, it won't be found. It will also returnnull
s if the fields have them set as the value. I have no idea what this will do about primitive types.Disclaimer: Code was tested briefly on an optimistic example, I hold no responsibility if it causes your computer to catch fire.
是这个方法你在找什么?
Is this method what you're looking for?