Richard Silvertass Richard Silvertass -4 years ago 139
Java Question

Java reflection: Get inner instantiated field

I have an interface which looks like this:

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


Is there any way I can access the Cat object through reflection?

I have tried this:

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


But it gives me a ClassNotFoundException.

Thanks in advance!

Answer Source

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 is then it needs to be added)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download