Java reflection: get internal field of an instance

I have an interface that looks like this:

public interface A {
    public interface B {
        public static final Cat cat = new Cat("Alice");
    }
}

      

Is there a way to access the Cat object through reflection?

I've tried this:

Field catField = Class.forName("A.B").getField("cat");

      

But this gives me a ClassNotFoundException.

Thanks in advance!

+3


source to share


3 answers


The syntax for this is:

Field catField = Class.forName("com.xx.A$B").getField("cat");
System.out.println(catField.toString());

      



(I can't tell if your package declaration is missing or not if it needs to be added)

+2


source


You need to use the syntax Outer$Inner

with reflection, not Outer.Inner

.



+3


source


You must use InterfaceName.class

.

    Class cat;
    try {
        cat = A.B.class;
        Field catField = cat.getField("cat");
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    }

      

0


source







All Articles