Lasirana Lasirana - 2 months ago 13
Java Question

Java Reflection - Instantiation Exception Interface

How can I realize with Java Reflection this case:

RequestDocument req = RequestDocument.Factory.newInstance();


I know how I can search a class and instantiate it but in this case I am unsure with the
.Factory.
before the new instance.

Answer

Assuming that Factory is a static nested class of RequestDocument and newInstance is a public static method, the equivalent of your code using reflection is then:

Object req = Class.forName("my.package.RequestDocument$Factory")
    .getMethod("newInstance")
    .invoke(null);

Please note the $ used to indicate that it is an inner class and null used as object on which we want to invoke the method because it is a static call so no instance is needed.

Comments