Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Please consider that generic-informations are erased by the compiler at compile-time and are replaced with object. Internally generics is just casting from and to java.lang.Object.</p> <p>This also why it's difficult to obtain generic information at runtime, even though it's possible.</p> <p>See here: <a href="https://www.google.de/#q=java+instantiate+generic+parameter&amp;oq=java+instantiate+generic+parameter" rel="nofollow">Google</a>.</p> <p>On a persopnal note: If you need to do anything like this, it is usually bad design. I was at this situation a couple of time, but I found a better solution every time :). So just consider if you really want such a dirty hack in your code.</p> <p><strong>Edit:</strong> Regarding to the comment section a more detailed explanation is needed.</p> <p>Reflection in general should be used with caution anyway, since from a software engineering point-of-view it is considered bad design. Why? It might introduce some hard to find bugs, since reflection alters the natural flow of your application and uses informations which are not always visible to you at development-time. This screams out for unexpected behavior.</p> <p>And even though I have no formal proof for this, but I state that each time you need reflection, there is another solution for your problem (if generative software-development is an option ;)).</p> <p>So in the end, in 99% of all cases reflection is nothing more then a dirty hack of a lazy programmar. This might be related to the fact that 100% of all programmars are lazy, but anyway.</p> <p><strong>Edit 2:</strong></p> <p>Since you want the code anyway:</p> <pre><code>abstract class Foo&lt;T&gt; { private Class&lt;T&gt; tClass; T field; public void bar(Class&lt;T&gt; clazz) { Type type = getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType)type; tClass = (Class&lt;T&gt;) paramType.getActualTypeArguments()[0]; field = tClass.newInstance(); } } } </code></pre> <p>(taken from: <a href="http://serdom.eu/ser/2007/03/25/java-generics-instantiating-objects-of-type-parameter-without-using-class-literal" rel="nofollow">Here</a>)</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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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