Reputation: 24691
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?
Upvotes: 3
Views: 133
Reputation: 140309
An interface is just a class for which Class.isInterface()
returns true. So:
Class<?>[] foo = {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
.
Upvotes: 10