Java generics - retrieve type

后端 未结 6 588
忘掉有多难
忘掉有多难 2020-12-18 04:18
public Interface Foo{...}

Is there a way to retrieve which T was given for an implementation of Foo?

For example,

相关标签:
6条回答
  • 2020-12-18 04:43

    Contrary to other answers, you can obtain the type of a generic parameter. For example, adding this to a method inside a generic class will obtain the first generic parameter of the class (T in your case):

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

    I use this technique in a generic Hibernate DAO I wrote so I can obtain the actual class being persisted because it is needed by Hibernate. It works!

    0 讨论(0)
  • 2020-12-18 04:47

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

    0 讨论(0)
  • 2020-12-18 04:56

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

    public Interface Foo<T extends Colors>{ public T returnType() {...} ...}
    
    0 讨论(0)
  • 2020-12-18 04:58

    There's. 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);
        }
    }
    
    0 讨论(0)
  • 2020-12-18 05:01

    EDIT

    Turns out for this case it is possible to get the generic information. Singleshot posted an answer which does just that. His should be the accepted answer. Re-qualifying mine.

    In general though, there are many cases where you are unable to get type information you might expect to be there. Java uses a technique called type erasure which removes the types from the generic at compile time. This prevents you from getting information about their actual binding at runtime in many scenarios.

    Nice FAQ on the subject:

    • http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html#Reflection
    0 讨论(0)
  • 2020-12-18 05:01

    One way to do this is to explicitly pass in a Class object with the 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 讨论(0)
提交回复
热议问题