英文:
How to get class in the field value using reflection?
问题
考虑以下代码:
class Foo {
   
}
class Bar {
    private Foo foo = new Foo();
}
在 Foo 类中是否有可能获取 foo 字段的类。我的意思是,在 Foo 类中是否可以获取 Bar 类。当然,这个问题涉及到反射,但不涉及 new Foo(Bar.class)。
英文:
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).
答案1
得分: 1
如果你想获取调用者的类(Caller's Class),你可以使用较新的(从Java 9开始引入的)[`StackWalker`][1] 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()` 方法。
[1]: https://download.java.net/java/GA/jdk14/docs/api/java.base/java/lang/StackWalker.html
英文:
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().
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论