How to get class in the field value using reflection?

iJava :

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).

Johannes Kuhn :

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().

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=397815&siteId=1