Reputation:
Consider the following code
class Foo {
}
class Bar {
private Foo foo = new Foo();
}
Is it possible in Foo
class to get the class of foo
field. I mean, I want in Foo
to get Bar
class. The question is of course about reflection, but not about new Foo(Bar.class)
.
Upvotes: 0
Views: 83
Reputation: 15192
If you want to get the callers Class, you can use the newish (introduced in Java 9) StackWalker
API:
class Foo {
private static final StackWalker SW = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
public Foo() {
Class<?> bar = SW.getCallerClass();
}
}
class Bar {
private Foo foo = new Foo();
}
If you use an older Java version, there is the unsupported sun.reflect.Reflection.getCallerClass()
.
Upvotes: 0