Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Generics: Accessing Generic Type at runtime
    primarykey
    data
    text
    <p>I'm looking to access the generic type of a declared field during runtime. I was previously under the impression that this was not possible due to the Java type erasure. However, this must not be the case because some well known frameworks leverage the generic type through reflection during runtime.</p> <p>As an example, Guice will implement a Provider based upon the generic type you provide:</p> <pre><code>public class Injectable{ @Inject private Provider&lt;SomeType&gt; someTypeProvider; } </code></pre> <p>How does one access the 'SomeType' generic attribute of a field or any such type/method/etc through the reflection API?</p> <p>Additionally it would be helpful to also know how to access these generic type attributes through the Java 6 Annotation Processor API.</p> <p>Thanks.</p> <p><strong>Edit:</strong></p> <p>Thank you all for your great pointers. I found a way to do this using haylem's links, specifically the one to Prenkov's article <a href="http://tutorials.jenkov.com/java-reflection/generics.html">Java Reflection: Generics</a>.</p> <p>Here's the answer I was looking for:</p> <pre><code>/** * @author John Ericksen */ public class TypeReflectionExample { public class SomeType{} public class Injectable{ @Inject private Provider&lt;SomeType&gt; someTypeProvider; } public static void main(String[] args){ try { Field providerField = Injectable.class.getDeclaredField("someTypeProvider"); Type genericFieldType = providerField.getGenericType(); if(genericFieldType instanceof ParameterizedType){ ParameterizedType aType = (ParameterizedType) genericFieldType; Type[] fieldArgTypes = aType.getActualTypeArguments(); for(Type fieldArgType : fieldArgTypes){ Class fieldArgClass = (Class) fieldArgType; System.out.println("fieldArgClass = " + fieldArgClass); } } } catch (NoSuchFieldException e) { e.printStackTrace(); } } } </code></pre> <p>results in:</p> <blockquote> <p>fieldArgClass = class test.TypeReflectionExample$SomeType</p> </blockquote> <p>The same can be done for Methods, Constructors, Superclass extensions/implements, etc</p> <p>I'm awarding haylem, as his post led me to this solution, even if it didn't directly answer my question.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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