简体   繁体   English

从抽象类获取字段实例

[英]Get field instance from abstract class

Given, for example, a class like this: 例如,给定一个这样的类:

public abstract class AbstractSomething {

    public static volatile SingularAttribute<Somefield, AnotherField> myAttribute;
}

how can I get an instance of myAttribute via reflection. 如何通过反射获取myAttribute的实例。 There are no implementing classes for AbstractSomething . 没有AbstractSomething实现类。


EDIT 编辑

No, we need an instance of the SingularAttribute<T, S> . 不,我们需要SingularAttribute<T, S>的实例。 And the reason we need to use reflection is becuase these classes are generated and passed into our method as a Class object. 我们之所以需要使用反射,是因为生成了这些类并将它们作为Class对象传递给我们的方法。 We have no way no know which AbstractSomething we are receiving. 我们无法知道我们正在接收哪个AbstractSomething There are quite a few of them. 有很多。


EDIT 2 编辑2

Found out what the issue was. 找出问题所在。 When a Hibernate context is present in the application, the interfaces on the abstract class are replaced with their implementation counterparts when accessing them. 当应用程序中存在Hibernate上下文时,访问它们时,抽象类上的接口将替换为其实现的对应对象。

No big deal actually, you can do something like this: 实际上没什么大不了的,您可以执行以下操作:

Field field = AbstractSomething.class.getField("myAttribute")

And then you can access it by invoking field.get(null) and field.set(null, value) 然后您可以通过调用field.get(null)field.set(null, value)来访问它

The real question is WHY do you want to use reflection, but I guess you have your reasons. 真正的问题是为什么要使用反射,但是我想您有理由。

EDIT: 编辑:

If you have a Class instance in before hand (lets call it classInstance) then you can do 如果您之前有一个Class实例(我们称其为classInstance),则可以

Field field = classInstance.getField("myAttribute")

to get the Field that reificates the field you are looking for... and if you want all fields just invoke the getFields method. 以获取可丰富您要查找的字段的字段...,如果您希望所有字段都只需调用getFields方法。

You don't really need a concrete implementation nor an instance of the reificated class in question in order to access the static fields. 为了访问静态字段,您实际上并不需要具体的实现,也不需要相关的类的实例。

No need for reflection. 无需反思。 The field belongs to the class , and no matter how many subclasses there are, there is only one instance of the AbstractSomething class, so just: 该字段属于该类 ,并且不管有多少个子类, AbstractSomething类只有一个实例,因此:

SingularAttribute<Somefield, AnotherField> attr = AbstractSomething.myAttribute;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM