Java generation - type selection

public Interface Foo<T extends Colors>{...} 

Is there any way to get which T was given to implement Foo?

For example,

 public Class FooImpl implements Foo<Green>{..} 

Will return green color.

+6
java generics
source share
6 answers

Unlike other answers, you can get the type of the general parameter. For example, adding this to a method inside a universal class, you get the first general parameter of the class ( T in your case):

 ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); type.getActualTypeArguments()[0] 

I use this technique in general Hibernate DAO, which I wrote to get a real class that is saved because Hibernate needs it. He works!

+15
source share

EDIT

It turned out that for this case you can get general information. Singleshot posted an answer that does just that. He must accept the accepted answer. Re-qualification mine.

In general, there are many cases where you cannot get the type information that you might expect. Java uses a method called type erasure, which removes types from the generic at compile time. This prevents getting information about their actual binding at run time in many scenarios.

Nice FAQ on the topic:

+9
source share

In the same place. Take a look at [Javadoc for java.lang.Class # getGenericInterfaces ()] ( http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getGenericInterfaces ()) .

Like this:

 public class Test1 { interface GenericOne<T> { } public class Impl implements GenericOne<Long> { } public static void main(String[] argv) { Class c = (Class) ((ParameterizedType) Impl.class.getGenericInterfaces()[0]).getActualTypeArguments()[0]; System.out.println(c); } } 
+1
source share

One way to do this is to explicitly pass a class object with a type. Something like the following:

 public class FooImpl<T extends Colors> { private Class<T> colorClass; public FooImpl(T colorClass) { this.colorClass = colorClass; } public Class<T> getColorClass() { return colorClass; } } 
0
source share

Depending on what you mean. Just T might be what you want, for example:

 public Interface Foo<T extends Colors>{ public T returnType() {...} ...} 
0
source share

[edit] Well, apparently, partially possible. A good explanation of how to do this (including an improvement on the method posted by SingleShot): http://www.artima.com/weblogs/viewpost.jsp?thread=208860

-2
source share

All Articles