I want to check if a given Class is assignable to a java.util.Collection, and if so create a new instance of it.
I tried the following:
Class<?> clazz = ... // I got this from somewhere
if (!clazz.isInterface() && java.util.Collection.class.isAssignableFrom(clazz)) {
java.util.Collection<?> collection = clazz.newInstance();
}
Predictably it doesn't work, since it cannot convert to an unknown type to a java.util.Collection. I thought of adding a cast but that seems like a hack.
I also thought of doing this:
Class<? extends java.util.Collection<?>> collectionClass = Class<? extends java.util.Collection<?>> clazz;
java.util.Collection<?> collection = clazz.newInstance();
Now there's no need for the cast at newInstance but I still have to cast the Class object.
What's the right way to do this? Thanks.
(for clarity I removed the try/catch around newInstance in case I'm trying to instantiate an abstract class)