简体   繁体   中英

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. There are no implementing classes for AbstractSomething .


EDIT

No, we need an instance of the 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. We have no way no know which AbstractSomething we are receiving. There are quite a few of them.


EDIT 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.

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)

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

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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