考虑以下代码
class Foo {
}
class Bar {
private Foo foo = new Foo();
}
是否可以在Foo
类中获取foo
字段的类。我的意思是,我想在 Foo 中获取 Bar 类。问题当然是关于反射,而不是关于 new Foo(Bar.class)
。
最佳答案
如果想获取调用者Class,可以使用newish(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();
}
如果您使用较旧的 Java 版本,则存在不受支持的 sun.reflect.Reflection.getCallerClass()
。
关于java - 如何使用反射获取字段值中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61015214/