通过反射如何获取字段值中的类?

huangapple go评论92阅读模式
英文:

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&lt;?&gt; 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().

huangapple
  • 本文由 发表于 2020年4月3日 23:27:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/61015214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定