Java generics - retrieve type

后端 未结 6 601
忘掉有多难
忘掉有多难 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: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 {
        }
    
        public class Impl implements GenericOne {
        }
    
        public static void main(String[] argv) {
            Class c = (Class) ((ParameterizedType) Impl.class.getGenericInterfaces()[0]).getActualTypeArguments()[0];
            System.out.println(c);
        }
    }
    

提交回复
热议问题