Green Cloak Guy Green Cloak Guy - 6 months ago 10
Java Question

Java "Interface" class

In Java, there is a

Class
class that can be used to represent other classes without instantiating them. For example:

Class[] foo = { ArrayList.class, String.class, Character.class, Integer.class, MyCustomClass.class };
ArrayList bar = foo[0].newInstance();


would be valid code. I could also, for example, run through an array of
Object
s and do
instanceof
checks on all of them to the corresponding classes in the
foo
array, which has potential applications.

Does such a class exist in Java for interfaces? Is there some class for which I can do something resembling this:

Interface[] foo = {Comparable, List<String>, MyCustomInterface}


Since as of Java 8, Interfaces can now have static methods, this behavior could be useful, if bad practice. Does it exist?

Answer

An interface is just a class for which Class.isInterface() returns true. So:

Class<?>[] classes = {Comparable.class, List.class, MyCustomInterface.class};

Note that there is no generic class instance for, e.g. List<String>: it's just raw List.class.