Reputation: 20557
Is it possible in Java to get the 'parent' class of an object using an instance of it and its class type?
Lets say we have these two class types and the annotation type:
public class Foo{
}
public class Bar{
@TestAnnotation
public Foo mFoo = new Foo();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation{
}
I would want to get the Field
object of mFoo
using an instance of Foo
, otherwise null
, with this I would get the annotation using TestAnnotation test = field.TestAnnotation(SQLiteID.class);
The end result I want is to know whether the instance of Foo
is part of another type that contains a certain annotation
This seems rather far fetched so I don't expect it to be possible.
Upvotes: 1
Views: 3081
Reputation: 77177
This isn't possible in Java. It would be possible by writing a JVM agent but would probably have a severe performance penalty because of all the bookkeeping.
Upvotes: 1
Reputation: 61875
This is not possible/feasible in general.
The same object instance can have many names - that is, the same object can be assigned to many different static fields, instance fields, parameters, local variables (etc) simultaneously.
All "solutions" involve some form of iteration over all such variables, which is rarely feasible and such general designs should be avoided. Even with a reduced domain (such as with annotations) a similar issue remains - i.e. how to find all such roots (objects instances with members having a certain annotation) of said domain?
Upvotes: 4
Reputation: 279960
I would want to get the Field object of mFoo using an instance of Foo.
This is doing things backwards and not possible.
You can get the Field
of Bar
by testing its type and then try to retrieve a specific annotation
Field[] fields = Bar.class.getDeclaredFields();
for (Field field : fields) {
if (Foo.class.isAssignableFrom(field.getType())) {
TestAnnotation testAnnotation = field.getAnnotation(TestAnnotation.class);
System.out.println(testAnnotation); // might be null, if annotation doesn't exist
}
}
Now if you have an instance of Foo
you can also compare it to the field value of an instance of Bar
.
Upvotes: 2