Note that there are some explanatory texts on larger screens.

plurals
  1. POcan I reflectively instantiate a generic type in java?
    primarykey
    data
    text
    <p>Is it possible to reflectively instantiate a generic type in Java? Using the technique described <a href="http://www.velocityreviews.com/forums/t149816-generics-and-forname.html" rel="noreferrer">here</a> I get an error because class tokens cannot be generic. Take the example below. I want to instantiate some subclass of Creator that implements Creator. The actual class name is passed in as a command line argument. The idea is to be able to specify an implementation of Creator at runtime. Is there another way to accomplish what I'm trying to do here?</p> <pre><code>public interface Creator&lt;T&gt; { T create(); } public class StringCreator implements Creator&lt;String&gt; { public String create() { return new String(); } } public class FancyStringCreator implements Creator&lt;String&gt; { public String create() { return new StringBuffer().toString(); } } public static void main(String[] args) throws Exception { Class&lt;?&gt; someClass = Class.forName(args[0]); /*ERROR*/Class&lt;? extends Creator&lt;String&gt;&gt; creatorClass = someClass.asSubclass(Creator.class); Constructor&lt;? extends Creator&lt;String&gt;&gt; creatorCtor = creatorClass.getConstructor((Class&lt;?&gt;[]) null); Creator&lt;String&gt; creator = creatorCtor.newInstance((Object[]) null); } </code></pre> <p>Edit: I like Marcus' approach as being the most simple and pragmatic without circumventing the whole generics thing. I can use it in my situation because I can specify that the class passed must be a subclass of StringCreator. But as Ericson pointed out the generic information is still there at the type level, just not at the runtime level so it is still possible to reflectively examine whether a given class implements the correct generic type.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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