<p>Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is <code>no</code> (<em>due to type erasure</em>), but I'd be interested if anyone can see something I'm missing:</p>

<pre><code>class SomeContainer&lt;E&gt;
{
    E createContents()
    {
        return what???
    }
}
</code></pre>

<p>EDIT: It turns out that <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860" rel="noreferrer">Super Type Tokens</a> could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.</p>

<p>I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860" rel="noreferrer">Artima Article</a>.</p>

[{'answer_id': 75201, 'author': 'Adam Rosenfield', 'author_id': 9530, 'author_profile': 'https://Stackoverflow.com/users/9530', 'pm_score': 0, 'selected': False, 'text': "<p>As you said, you can't really do it because of type erasure.  You can sort of do it using reflection, but it requires a lot of code and lot of error handling.</p>\n"}, {'answer_id': 75254, 'author': 'Justin Rudd', 'author_id': 12968, 'author_profile': 'https://Stackoverflow.com/users/12968', 'pm_score': 9, 'selected': False, 'text': "<p>You are correct.  You can't do <code>new E()</code>.  But you can change it to</p>\n\n<pre><code>private static class SomeContainer&lt;E&gt; {\n    E createContents(Class&lt;E&gt; clazz) {\n        return clazz.newInstance();\n    }\n}\n</code></pre>\n\n<p>It's a pain.  But it works.  Wrapping it in the factory pattern makes it a little more tolerable.</p>\n"}, {'answer_id': 75313, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 3, 'selected': False, 'text': '<p>Here is an option I came up with, it may help:</p>\n\n<pre><code>public static class Container&lt;E&gt; {\n    private Class&lt;E&gt; clazz;\n\n    public Container(Class&lt;E&gt; clazz) {\n        this.clazz = clazz;\n    }\n\n    public E createContents() throws Exception {\n        return clazz.newInstance();\n    }\n}\n</code></pre>\n\n<p>EDIT: Alternatively you can use this constructor (but it requires an instance of E):</p>\n\n<pre><code>@SuppressWarnings("unchecked")\npublic Container(E instance) {\n    this.clazz = (Class&lt;E&gt;) instance.getClass();\n}\n</code></pre>\n'}, {'answer_id': 75345, 'author': 'noah', 'author_id': 12034, 'author_profile': 'https://Stackoverflow.com/users/12034', 'pm_score': 7, 'selected': False, 'text': "<p>I don't know if this helps, but when you subclass (including anonymously) a generic type, the type information is available via reflection. e.g.,</p>\n<pre><code>public abstract class Foo&lt;E&gt; {\n\n  public E instance;  \n\n  public Foo() throws Exception {\n    instance = ((Class)((ParameterizedType)this.getClass().\n       getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();\n    ...\n  }\n\n}\n</code></pre>\n<p>So, when you subclass Foo, you get an instance of Bar e.g.,</p>\n<pre><code>// notice that this in anonymous subclass of Foo\nassert( new Foo&lt;Bar&gt;() {}.instance instanceof Bar );\n</code></pre>\n<p>But it's a lot of work, and only works for subclasses. Can be handy though.</p>\n"}, {'answer_id': 75528, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 6, 'selected': False, 'text': "<p>You'll need some kind of abstract factory of one sort or another to pass the buck to:</p>\n\n<pre><code>interface Factory&lt;E&gt; {\n    E create();\n}\n\nclass SomeContainer&lt;E&gt; {\n    private final Factory&lt;E&gt; factory;\n    SomeContainer(Factory&lt;E&gt; factory) {\n        this.factory = factory;\n    }\n    E createContents() {\n        return factory.create();\n    }\n}\n</code></pre>\n"}, {'answer_id': 75595, 'author': 'Pavel Feldman', 'author_id': 5507, 'author_profile': 'https://Stackoverflow.com/users/5507', 'pm_score': 0, 'selected': False, 'text': '<p>If you mean \n<code>new E()</code> \nthen it is impossible. And I would add that it is not always correct - how do you know if E has public no-args constructor?\nBut you can always delegate creation to some other class that knows how to create an instance - it can be <code>Class&lt;E&gt;</code> or your custom code like this</p>\n\n<pre><code>interface Factory&lt;E&gt;{\n    E create();\n}    \n\nclass IntegerFactory implements Factory&lt;Integer&gt;{    \n  private static int i = 0; \n  Integer create() {        \n    return i++;    \n  }\n}\n</code></pre>\n'}, {'answer_id': 87187, 'author': 'jb.', 'author_id': 7918, 'author_profile': 'https://Stackoverflow.com/users/7918', 'pm_score': 3, 'selected': False, 'text': '<p>If you want not to type class name twice during instantiation like in:</p>\n\n<pre><code>new SomeContainer&lt;SomeType&gt;(SomeType.class);\n</code></pre>\n\n<p>You can use factory method:</p>\n\n<pre><code>&lt;E&gt; SomeContainer&lt;E&gt; createContainer(Class&lt;E&gt; class); \n</code></pre>\n\n<p>Like in:</p>\n\n<pre><code>public class Container&lt;E&gt; {\n\n    public static &lt;E&gt; Container&lt;E&gt; create(Class&lt;E&gt; c) {\n        return new Container&lt;E&gt;(c);\n    }\n\n    Class&lt;E&gt; c;\n\n    public Container(Class&lt;E&gt; c) {\n        super();\n        this.c = c;\n    }\n\n    public E createInstance()\n            throws InstantiationException,\n            IllegalAccessException {\n        return c.newInstance();\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 376216, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>You can use:</p>\n\n<pre><code>Class.forName(String).getConstructor(arguments types).newInstance(arguments)\n</code></pre>\n\n<p>But you need to supply the exact class name, including packages, eg. <code>java.io.FileInputStream</code>. I used this to create a math expressions parser.</p>\n'}, {'answer_id': 3635805, 'author': 'Lars Bohl', 'author_id': 438960, 'author_profile': 'https://Stackoverflow.com/users/438960', 'pm_score': 5, 'selected': False, 'text': '<pre><code>package org.foo.com;\n\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\n\n/**\n * Basically the same answer as noah\'s.\n */\npublic class Home&lt;E&gt;\n{\n\n    @SuppressWarnings ("unchecked")\n    public Class&lt;E&gt; getTypeParameterClass()\n    {\n        Type type = getClass().getGenericSuperclass();\n        ParameterizedType paramType = (ParameterizedType) type;\n        return (Class&lt;E&gt;) paramType.getActualTypeArguments()[0];\n    }\n\n    private static class StringHome extends Home&lt;String&gt;\n    {\n    }\n\n    private static class StringBuilderHome extends Home&lt;StringBuilder&gt;\n    {\n    }\n\n    private static class StringBufferHome extends Home&lt;StringBuffer&gt;\n    {\n    }   \n\n    /**\n     * This prints "String", "StringBuilder" and "StringBuffer"\n     */\n    public static void main(String[] args) throws InstantiationException, IllegalAccessException\n    {\n        Object object0 = new StringHome().getTypeParameterClass().newInstance();\n        Object object1 = new StringBuilderHome().getTypeParameterClass().newInstance();\n        Object object2 = new StringBufferHome().getTypeParameterClass().newInstance();\n        System.out.println(object0.getClass().getSimpleName());\n        System.out.println(object1.getClass().getSimpleName());\n        System.out.println(object2.getClass().getSimpleName());\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 5389482, 'author': 'Rachid', 'author_id': 670960, 'author_profile': 'https://Stackoverflow.com/users/670960', 'pm_score': 0, 'selected': False, 'text': '<pre><code>return   (E)((Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();\n</code></pre>\n'}, {'answer_id': 10042797, 'author': 'Bogdan Veliscu', 'author_id': 818753, 'author_profile': 'https://Stackoverflow.com/users/818753', 'pm_score': 0, 'selected': False, 'text': '<p>You can achieve this with the following snippet:</p>\n\n<pre><code>import java.lang.reflect.ParameterizedType;\n\npublic class SomeContainer&lt;E&gt; {\n   E createContents() throws InstantiationException, IllegalAccessException {\n      ParameterizedType genericSuperclass = (ParameterizedType)\n         getClass().getGenericSuperclass();\n      @SuppressWarnings("unchecked")\n      Class&lt;E&gt; clazz = (Class&lt;E&gt;)\n         genericSuperclass.getActualTypeArguments()[0];\n      return clazz.newInstance();\n   }\n   public static void main( String[] args ) throws Throwable {\n      SomeContainer&lt; Long &gt; scl = new SomeContainer&lt;&gt;();\n      Long l = scl.createContents();\n      System.out.println( l );\n   }\n}\n</code></pre>\n'}, {'answer_id': 12407106, 'author': 'Sergiy Sokolenko', 'author_id': 131337, 'author_profile': 'https://Stackoverflow.com/users/131337', 'pm_score': 4, 'selected': False, 'text': '<p>From <a href="http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html" rel="nofollow noreferrer">Java Tutorial - Restrictions on Generics</a>:</p>\n<p><strong><a href="http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createObjects" rel="nofollow noreferrer">Cannot Create Instances of Type Parameters</a></strong></p>\n<p>You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:</p>\n<pre><code>public static &lt;E&gt; void append(List&lt;E&gt; list) {\n    E elem = new E();  // compile-time error\n    list.add(elem);\n}\n</code></pre>\n<p>As a workaround, you can create an object of a type parameter through reflection:</p>\n<pre><code>public static &lt;E&gt; void append(List&lt;E&gt; list, Class&lt;E&gt; cls) throws Exception {\n    E elem = cls.getDeclaredConstructor().newInstance();   // OK\n    list.add(elem);\n}\n</code></pre>\n<p>You can invoke the append method as follows:</p>\n<pre><code>List&lt;String&gt; ls = new ArrayList&lt;&gt;();\nappend(ls, String.class);\n</code></pre>\n'}, {'answer_id': 14146479, 'author': 'Luigi R. Viggiano', 'author_id': 258289, 'author_profile': 'https://Stackoverflow.com/users/258289', 'pm_score': 2, 'selected': False, 'text': '<p>I thought I could do that, but quite disappointed: it doesn\'t work, but I think it still worths sharing. </p>\n\n<p>Maybe someone can correct:</p>\n\n<pre><code>import java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\n\ninterface SomeContainer&lt;E&gt; {\n    E createContents();\n}\n\npublic class Main {\n\n    @SuppressWarnings("unchecked")\n    public static &lt;E&gt; SomeContainer&lt;E&gt; createSomeContainer() {\n        return (SomeContainer&lt;E&gt;) Proxy.newProxyInstance(Main.class.getClassLoader(),\n                new Class[]{ SomeContainer.class }, new InvocationHandler() {\n            @Override\n            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n                Class&lt;?&gt; returnType = method.getReturnType();\n                return returnType.newInstance();\n            }\n        });\n    }\n\n    public static void main(String[] args) {\n        SomeContainer&lt;String&gt; container = createSomeContainer();\n\n    [*] System.out.println("String created: [" +container.createContents()+"]");\n\n    }\n}\n</code></pre>\n\n<p>It produces:</p>\n\n<pre><code>Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String\n    at Main.main(Main.java:26)\n    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n    at java.lang.reflect.Method.invoke(Method.java:601)\n    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)\n</code></pre>\n\n<p>Line 26 is the one with the <code>[*]</code>.</p>\n\n<p>The only viable solution is the one by @JustinRudd</p>\n'}, {'answer_id': 14191442, 'author': 'R2D2M2', 'author_id': 1949703, 'author_profile': 'https://Stackoverflow.com/users/1949703', 'pm_score': 5, 'selected': False, 'text': "<p>If you need a new instance of a type argument inside a generic class then make your constructors demand its class...</p>\n\n<pre><code>public final class Foo&lt;T&gt; {\n\n    private Class&lt;T&gt; typeArgumentClass;\n\n    public Foo(Class&lt;T&gt; typeArgumentClass) {\n\n        this.typeArgumentClass = typeArgumentClass;\n    }\n\n    public void doSomethingThatRequiresNewT() throws Exception {\n\n        T myNewT = typeArgumentClass.newInstance();\n        ...\n    }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Foo&lt;Bar&gt; barFoo = new Foo&lt;Bar&gt;(Bar.class);\nFoo&lt;Etc&gt; etcFoo = new Foo&lt;Etc&gt;(Etc.class);\n</code></pre>\n\n<p>Pros:</p>\n\n<ul>\n<li>Much simpler (and less problematic) than Robertson's Super Type Token (STT) approach.</li>\n<li>Much more efficient than the STT approach (which will eat your cellphone for breakfast).</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>Can't pass Class to a default constructor (which is why Foo is final). If you really do need a default constructor you can always add a setter method but then you must remember to give her a call later.</li>\n<li>Robertson's objection... More Bars than a black sheep (although specifying the type argument class one more time won't exactly kill you). And contrary to Robertson's claims this does not violate the DRY principal anyway because the compiler will ensure type correctness.</li>\n<li>Not entirely <code>Foo&lt;L&gt;</code>proof. For starters... <code>newInstance()</code> will throw a wobbler if the type argument class does not have a default constructor. This does apply to all known solutions though anyway.</li>\n<li>Lacks the total encapsulation of the STT approach. Not a big deal though (considering the outrageous performance overhead of STT).</li>\n</ul>\n"}, {'answer_id': 21553287, 'author': 'Roald', 'author_id': 2344378, 'author_profile': 'https://Stackoverflow.com/users/2344378', 'pm_score': -1, 'selected': False, 'text': '<p>You can with a classloader and the class name, eventually some parameters.</p>\n\n<pre><code>final ClassLoader classLoader = ...\nfinal Class&lt;?&gt; aClass = classLoader.loadClass("java.lang.Integer");\nfinal Constructor&lt;?&gt; constructor = aClass.getConstructor(int.class);\nfinal Object o = constructor.newInstance(123);\nSystem.out.println("o = " + o);\n</code></pre>\n'}, {'answer_id': 21716855, 'author': 'Ira', 'author_id': 3299647, 'author_profile': 'https://Stackoverflow.com/users/3299647', 'pm_score': 3, 'selected': False, 'text': "<p>When you are working with E at compile time you don't really care the actual generic type &quot;E&quot; (either you use reflection or work with base class of generic type) so let the subclass provide instance of E.</p>\n<pre><code>abstract class SomeContainer&lt;E&gt;\n{\n    abstract protected E createContents();\n    public void doWork(){\n        E obj = createContents();\n        // Do the work with E \n     }\n}\n\nclass BlackContainer extends SomeContainer&lt;Black&gt;{\n    protected Black createContents() {\n        return new Black();\n    }\n}\n</code></pre>\n"}, {'answer_id': 25195050, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>You can do this now and it doesn\'t require a bunch of reflection code.</p>\n\n<pre><code>import com.google.common.reflect.TypeToken;\n\npublic class Q26289147\n{\n    public static void main(final String[] args) throws IllegalAccessException, InstantiationException\n    {\n        final StrawManParameterizedClass&lt;String&gt; smpc = new StrawManParameterizedClass&lt;String&gt;() {};\n        final String string = (String) smpc.type.getRawType().newInstance();\n        System.out.format("string = \\"%s\\"",string);\n    }\n\n    static abstract class StrawManParameterizedClass&lt;T&gt;\n    {\n        final TypeToken&lt;T&gt; type = new TypeToken&lt;T&gt;(getClass()) {};\n    }\n}\n</code></pre>\n\n<p>Of course if you need to call the constructor that will require some reflection, but that is very well documented, this trick isn\'t!</p>\n\n<p>Here is the <a href="https://google.github.io/guava/releases/19.0/api/docs/com/google/common/reflect/TypeToken.html" rel="noreferrer">JavaDoc for TypeToken</a>.</p>\n'}, {'answer_id': 26796874, 'author': 'Amio.io', 'author_id': 1075289, 'author_profile': 'https://Stackoverflow.com/users/1075289', 'pm_score': 2, 'selected': False, 'text': "<p>An imporovement of @Noah's answer. </p>\n\n<p><strong>Reason for Change</strong></p>\n\n<p><strong>a]</strong> Is safer if more then 1 generic type is used in case you changed the order.</p>\n\n<p><strong>b]</strong> A class generic type signature changes from time to time so that you will not be surprised by unexplained exceptions in the runtime.</p>\n\n<p><strong>Robust Code</strong></p>\n\n<pre><code>public abstract class Clazz&lt;P extends Params, M extends Model&gt; {\n\n    protected M model;\n\n    protected void createModel() {\n    Type[] typeArguments = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();\n    for (Type type : typeArguments) {\n        if ((type instanceof Class) &amp;&amp; (Model.class.isAssignableFrom((Class) type))) {\n            try {\n                model = ((Class&lt;M&gt;) type).newInstance();\n            } catch (InstantiationException | IllegalAccessException e) {\n                throw new RuntimeException(e);\n            }\n        }\n    }\n}\n</code></pre>\n\n<p>Or use the one liner</p>\n\n<p><strong>One Line Code</strong></p>\n\n<pre><code>model = ((Class&lt;M&gt;) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]).newInstance();\n</code></pre>\n"}, {'answer_id': 29680588, 'author': 'Ingo', 'author_id': 86604, 'author_profile': 'https://Stackoverflow.com/users/86604', 'pm_score': 4, 'selected': False, 'text': '<p>Think about a more functional approach: instead of creating some E  out of nothing (which is clearly a code smell), pass a function that knows how to create one, i.e.</p>\n\n<pre><code>E createContents(Callable&lt;E&gt; makeone) {\n     return makeone.call(); // most simple case clearly not that useful\n}\n</code></pre>\n'}, {'answer_id': 35315432, 'author': 'Neepsnikeep', 'author_id': 5507619, 'author_profile': 'https://Stackoverflow.com/users/5507619', 'pm_score': 3, 'selected': False, 'text': '<p>Java unfortunatly does not allow what you want to do. See the <a href="http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createObjects" rel="nofollow noreferrer">official workaround</a> :</p>\n\n<blockquote>\n  <p>You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:</p>\n</blockquote>\n\n<pre><code>public static &lt;E&gt; void append(List&lt;E&gt; list) {\n    E elem = new E();  // compile-time error\n    list.add(elem);\n}\n</code></pre>\n\n<blockquote>\n  <p>As a workaround, you can create an object of a type parameter through reflection:</p>\n</blockquote>\n\n<pre><code>public static &lt;E&gt; void append(List&lt;E&gt; list, Class&lt;E&gt; cls) throws Exception {\n    E elem = cls.newInstance();   // OK\n    list.add(elem);\n}\n</code></pre>\n\n<blockquote>\n  <p>You can invoke the append method as follows:</p>\n</blockquote>\n\n<pre><code>List&lt;String&gt; ls = new ArrayList&lt;&gt;();\nappend(ls, String.class);\n</code></pre>\n'}, {'answer_id': 36315051, 'author': 'Daniel Pryden', 'author_id': 128397, 'author_profile': 'https://Stackoverflow.com/users/128397', 'pm_score': 7, 'selected': False, 'text': '<p>In Java 8 you can use the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html" rel="noreferrer"><code>Supplier</code></a> functional interface to achieve this pretty easily:</p>\n\n<pre><code>class SomeContainer&lt;E&gt; {\n  private Supplier&lt;E&gt; supplier;\n\n  SomeContainer(Supplier&lt;E&gt; supplier) {\n    this.supplier = supplier;\n  }\n\n  E createContents() {\n    return supplier.get();\n  }\n}\n</code></pre>\n\n<p>You would construct this class like this:</p>\n\n<pre><code>SomeContainer&lt;String&gt; stringContainer = new SomeContainer&lt;&gt;(String::new);\n</code></pre>\n\n<p>The syntax <code>String::new</code> on that line is a <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html" rel="noreferrer">constructor reference</a>.</p>\n\n<p>If your constructor takes arguments you can use a lambda expression instead:</p>\n\n<pre><code>SomeContainer&lt;BigInteger&gt; bigIntegerContainer\n    = new SomeContainer&lt;&gt;(() -&gt; new BigInteger(1));\n</code></pre>\n'}, {'answer_id': 53955316, 'author': 'Alexandr', 'author_id': 511804, 'author_profile': 'https://Stackoverflow.com/users/511804', 'pm_score': 0, 'selected': False, 'text': '<p>Here is an improved solution, based on <code>ParameterizedType.getActualTypeArguments</code>, already mentioned by @noah, @Lars Bohl, and some others. </p>\n\n<p>First small improvement in the implementation. Factory should not return instance, but a type. As soon as you return instance using <code>Class.newInstance()</code> you reduce a scope of usage. Because only no-arguments constructors can be invoke like this. A better way is to return a type, and allow a client to choose, which constructor he wants to invoke:</p>\n\n<pre><code>public class TypeReference&lt;T&gt; {\n  public Class&lt;T&gt; type(){\n    try {\n      ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();\n      if (pt.getActualTypeArguments() == null || pt.getActualTypeArguments().length == 0){\n        throw new IllegalStateException("Could not define type");\n      }\n      if (pt.getActualTypeArguments().length != 1){\n        throw new IllegalStateException("More than one type has been found");\n      }\n      Type type = pt.getActualTypeArguments()[0];\n      String typeAsString = type.getTypeName();\n      return (Class&lt;T&gt;) Class.forName(typeAsString);\n\n    } catch (Exception e){\n      throw new IllegalStateException("Could not identify type", e);\n    }\n\n  }\n}\n</code></pre>\n\n<p>Here is a usage examples. @Lars Bohl has shown only a signe way to get reified geneneric via extension. @noah only via creating an instance with <code>{}</code>. Here are tests to demonstrate both cases:</p>\n\n<pre><code>import java.lang.reflect.Constructor;\n\npublic class TypeReferenceTest {\n\n  private static final String NAME = "Peter";\n\n  private static class Person{\n    final String name;\n\n    Person(String name) {\n      this.name = name;\n    }\n  }\n\n  @Test\n  public void erased() {\n    TypeReference&lt;Person&gt; p = new TypeReference&lt;&gt;();\n    Assert.assertNotNull(p);\n    try {\n      p.type();\n      Assert.fail();\n    } catch (Exception e){\n      Assert.assertEquals("Could not identify type", e.getMessage());\n    }\n  }\n\n  @Test\n  public void reified() throws Exception {\n    TypeReference&lt;Person&gt; p = new TypeReference&lt;Person&gt;(){};\n    Assert.assertNotNull(p);\n    Assert.assertEquals(Person.class.getName(), p.type().getName());\n    Constructor ctor = p.type().getDeclaredConstructor(NAME.getClass());\n    Assert.assertNotNull(ctor);\n    Person person = (Person) ctor.newInstance(NAME);\n    Assert.assertEquals(NAME, person.name);\n  }\n\n  static class TypeReferencePerson extends TypeReference&lt;Person&gt;{}\n\n  @Test\n  public void reifiedExtenension() throws Exception {\n    TypeReference&lt;Person&gt; p = new TypeReferencePerson();\n    Assert.assertNotNull(p);\n    Assert.assertEquals(Person.class.getName(), p.type().getName());\n    Constructor ctor = p.type().getDeclaredConstructor(NAME.getClass());\n    Assert.assertNotNull(ctor);\n    Person person = (Person) ctor.newInstance(NAME);\n    Assert.assertEquals(NAME, person.name);\n  }\n}\n</code></pre>\n\n<p><strong>Note:</strong> you can force the clients of <code>TypeReference</code> always use <code>{}</code> when instance is created by making this class abstract: <code>public abstract class TypeReference&lt;T&gt;</code>. I\'ve not done it, only to show erased test case. </p>\n'}, {'answer_id': 54213575, 'author': 'Se Song', 'author_id': 3458608, 'author_profile': 'https://Stackoverflow.com/users/3458608', 'pm_score': 3, 'selected': False, 'text': "<p>Hope this's not too late to help!!!</p>\n<p>Java is type-safe, meaning that only Objects are able to create instances.</p>\n<p>In my case I cannot pass parameters to the <code>createContents</code> method. My solution is using extends unlike the answer below.</p>\n<pre><code>private static class SomeContainer&lt;E extends Object&gt; {\n    E e;\n    E createContents() throws Exception{\n        return (E) e.getClass().getDeclaredConstructor().newInstance();\n    }\n}\n</code></pre>\n<p>This is my example case in which I can't pass parameters.</p>\n<pre><code>public class SomeContainer&lt;E extends Object&gt; {\n    E object;\n\n    void resetObject throws Exception{\n        object = (E) object.getClass().getDeclaredConstructor().newInstance();\n    }\n}\n</code></pre>\n<p>Using reflection create run time error, if you extends your generic class with none object type. To extends your generic type to object convert this error to compile time error.</p>\n"}, {'answer_id': 57112253, 'author': 'Sudhanshu Jain', 'author_id': 6685277, 'author_profile': 'https://Stackoverflow.com/users/6685277', 'pm_score': 2, 'selected': False, 'text': '<p>what you can do is -</p>\n\n<ol>\n<li><p>First declare the variable of that generic  class </p>\n\n<p>2.Then make a constructor of it and instantiate that object</p></li>\n<li><p>Then use it wherever you want to use it</p></li>\n</ol>\n\n<p>example-</p>\n\n<p>1 </p>\n\n<blockquote>\n  <p><code>private Class&lt;E&gt; entity;</code></p>\n</blockquote>\n\n<p>2 </p>\n\n<pre><code>public xyzservice(Class&lt;E&gt; entity) {\n        this.entity = entity;\n    }\n\n\n\npublic E getEntity(Class&lt;E&gt; entity) throws InstantiationException, IllegalAccessException {\n        return entity.newInstance();\n    }\n</code></pre>\n\n<p>3.</p>\n\n<blockquote>\n  <p>E e = getEntity(entity);</p>\n</blockquote>\n'}, {'answer_id': 57125467, 'author': 'cacheoff', 'author_id': 2549901, 'author_profile': 'https://Stackoverflow.com/users/2549901', 'pm_score': 2, 'selected': False, 'text': '<p>Use the <a href="https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/reflect/TypeToken.html" rel="nofollow noreferrer"><code>TypeToken&lt;T&gt;</code></a> class:</p>\n\n<pre><code>public class MyClass&lt;T&gt; {\n    public T doSomething() {\n        return (T) new TypeToken&lt;T&gt;(){}.getRawType().newInstance();\n    }\n}\n</code></pre>\n'}, {'answer_id': 67363847, 'author': 'Braian Coronel', 'author_id': 5279996, 'author_profile': 'https://Stackoverflow.com/users/5279996', 'pm_score': 0, 'selected': False, 'text': '<p>Note that a generic type in kotlin could come without a default constructor.</p>\n<pre><code> implementation(&quot;org.objenesis&quot;,&quot;objenesis&quot;, &quot;3.2&quot;)\n</code></pre>\n<hr />\n<pre><code>    val fooType = Foo::class.java\n    var instance: T = try {\n        fooType.newInstance()\n    } catch (e: InstantiationException) {\n//            Use Objenesis because the fooType class has not a default constructor\n        val objenesis: Objenesis = ObjenesisStd()\n        objenesis.newInstance(fooType)\n    }\n</code></pre>\n<ul>\n<li><a href="https://stackoverflow.com/q/4133709/5279996">Withou default constructor</a></li>\n<li><a href="http://objenesis.org/tutorial.html" rel="nofollow noreferrer">Objenesis</a></li>\n</ul>\n'}, {'answer_id': 68001457, 'author': 'michal.jakubeczy', 'author_id': 2470765, 'author_profile': 'https://Stackoverflow.com/users/2470765', 'pm_score': 0, 'selected': False, 'text': "<p>I was inspired with Ira's solution and slightly modified it.</p>\n<pre><code>abstract class SomeContainer&lt;E&gt;\n{\n    protected E createContents() {\n        throw new NotImplementedException();\n    }\n\n    public void doWork(){\n        E obj = createContents();\n        // Do the work with E \n     }\n}\n\nclass BlackContainer extends SomeContainer&lt;Black&gt;{\n    // this method is optional to implement in case you need it\n    protected Black createContents() {\n        return new Black();\n    }\n}\n</code></pre>\n<p>In case you need <code>E</code> instance you can implement <code>createContents</code> method in your derived class (or leave it not implemented in case you don't need it.</p>\n"}]
['https://Stackoverflow.com/questions/75175', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5309/']