例子:
1 private static <T> T getObject(Class<T> o) throws Exception{//定义了一个泛型方法 2 T t=o.newInstance(); 3 return t; 4 } 5 6 static class Book<M>{//定义了一个泛型类 7 private M name; 8 9 public M getName() { 10 return name; 11 } 12 13 public void setName(M name) { 14 this.name = name; 15 } 16 } 1 public static void main(String[] args) throws Exception { 2 Book<String> b=new Book<String>(); 3 b.setName("a"); 4 Book<Integer> b1=new Book<Integer>(); 5 b1.setName(2); 6 System.out.println(b.getName()); 7 System.out.println(b.getClass()==b1.getClass()); 8 9 }运行结果为true.
泛型常见什么T、K、V、E这种符号是参数的形式参数,自己也可以定义成什么M、N之类的。符号?使用是在当我们类型不能确定时使用,也就是通配符。
要多学习。。。。。。
转载于:https://www.cnblogs.com/huzi007/p/5175693.html
相关资源:JAVA泛型加减乘除