I am having trouble accessing the runtime type of id
via reflection from MyClass
.
public abstract class AbstractEntity<T> {
@Id
private T id; //I need to access the runtime class of T
}
public class MyClass extends AbstractEntity<Long> {}
I am using java reflection and have access to the id Field
in the superclass.
I tried using:
field.getGenericType()
: which returnsTypeVariableImpl
with a valueT
.field.getType()
which returnsObject
.
I want to access Long
as the field type.
I am writing a library for others to use and there are a few issues:
- I don't actually know if the type is a generic type or a regular type, I only know it is annotated with
@id
. - I don't know where in the class hierarchy this field is located.
Here is the method I am using to get hold of all fields in the class hierarchy.
private Set<Field> getAllFields(final Object object) {
final Set<Field> fields = new HashSet<>();
fields.addAll(Arrays.asList(object.getClass().getDeclaredFields()));
Class<?> superclass = object.getClass().getSuperclass();
while (superclass != null) {
fields.addAll(Arrays.asList(superclass.getDeclaredFields()));
superclass = superclass.getSuperclass();
}
return fields;
}
I then filter this list for field annotated with @Id
of which there should only be one.
Aucun commentaire:
Enregistrer un commentaire