Roddy of the Frozen Peas Roddy of the Frozen Peas - 1 year ago 69
Java Question

Can I directly instantiate an interface using Java reflection?

I'm dealing with a contractor's code. For whatever reason he has made a series of "constants" files that are all interfaces. They look like this:

interface SomeTypeConsts {
public static class SomeSubTypeA {
public static final String CONSTANT_A = "foo";
public static final String CONSTANT_B = "bar";
public static class SomeSubTypeB {
public static final String CONSTANT_A = "baz";

and so forth. There are no unimplemented/abstract methods, the files just contain nested classes some arbitrary level deep, and static final Strings for the constants. I cannot modify the contractor's code at this time.

I'm writing a test framework and I need an instance of one of these constants interfaces. All of them follow the above pattern, but my method needs to support all of them and not just one in specific.

I tried instantiating the interface using Reflection like this:

clazz.newInstance() // where clazz is Class<SomeTypeConsts>

But it threw a

All of the questions here on SO say that you need to implement the interface first, then use that instance. And if I knew ahead of time which const interface it was, I could easily do
SomeTypeConsts consts = new SomeTypeConsts(){};
. But I haven't been able to figure out how to do this with reflection, when all I have to work with is the

Given an interface Class reference, with no abstract methods to be overwritten/implemented, how can I instantiate an instance of it using reflection?

Answer Source

From the language spec (emphasis mine):

This type has no instance variables, and typically declares one or more abstract methods; otherwise unrelated classes can implement the interface by providing implementations for its abstract methods. Interfaces may not be directly instantiated.

And, from the Javadoc of Class.newInstance():

[throws] InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.

You can't instantiate an interface. You can only instantiate (non-abstract) classes which implement it.

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