欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

泛型的使用

程序员文章站 2022-04-05 18:00:34
...
public class ClassTest {
  public static void main(String[] args) throws Exception {
    ParameterizedType type = (ParameterizedType) 
       Bar.class.getGenericSuperclass();
    System.out.println(type.getActualTypeArguments()[0]);
 
    ParameterizedType fieldType = (ParameterizedType) 
        Foo.class.getField("children").getGenericType();
    System.out.println(fieldType.getActualTypeArguments()[0]);
 
    ParameterizedType paramType = (ParameterizedType) 
        Foo.class.getMethod("foo", List.class)
        .getGenericParameterTypes()[0];
    System.out.println(paramType.getActualTypeArguments()[0]);
 
    System.out.println(Foo.class.getTypeParameters()[0]
        .getBounds()[0]);
  }
 
  class Foo<E extends CharSequence> {
    public List<Bar> children = new ArrayList<Bar>();
    public List<StringBuilder> foo(List<String> foo) {return null; }
    public void bar(List<? extends String> param) {}
  }
 
  class Bar extends Foo<String> {}
}

 

 

class java.lang.String
class ClassTest$Bar
class java.lang.String
class java.lang.StringBuilder
interface java.lang.CharSequence

 

相关标签: 泛型