Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This will do what you are trying to do while providing type safety. There's no way to avoid an unchecked warning, but the type checking done here justifies its suppression.</p> <pre><code> public static void main(String[] args) throws Exception { Class&lt;? extends Creator&lt;String&gt;&gt; clz = load(argv[0], String.class); Constructor&lt;? extends Creator&lt;String&gt;&gt; ctor = clz.getConstructor(); Creator&lt;String&gt; creator = ctor.newInstance(); System.out.println(creator.create()); } public static &lt;T&gt; Class&lt;? extends Creator&lt;T&gt;&gt; load(String fqcn, Class&lt;T&gt; type) throws ClassNotFoundException { Class&lt;?&gt; any = Class.forName(fqcn); for (Class&lt;?&gt; clz = any; clz != null; clz = clz.getSuperclass()) { for (Object ifc : clz.getGenericInterfaces()) { if (ifc instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) ifc; if (Creator.class.equals(pType.getRawType())) { if (!pType.getActualTypeArguments()[0].equals(type)) throw new ClassCastException("Class implements " + pType); /* We've done the necessary checks to show that this is safe. */ @SuppressWarnings("unchecked") Class&lt;? extends Creator&lt;T&gt;&gt; creator = (Class&lt;? extends Creator&lt;T&gt;&gt;) any; return creator; } } } } throw new ClassCastException(fqcn + " does not implement Creator&lt;String&gt;"); } </code></pre> <p>The main restriction you have to adhere to is that a class in the hierarchy must specify the type parameter. For example <code>class MyCreator implements Creator&lt;String&gt;</code>. You can't use it with <code>class GenericCreator&lt;T&gt; implements Creator&lt;T&gt;</code>. </p> <p>It doesn't currently handle the valid case where you create a new interface <code>interface StringCreatorIfc extends Creator&lt;String&gt;</code>, and have a class implement that. It could be enhanced to do that, but I'll leave that as an exercise for those inclined.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload