`
kuyuyingzi
  • 浏览: 53524 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

黑马程序员---泛型与泛型的反射

 
阅读更多

------------- java培训、android培训、java博客、java学习型技术博客、期待与您交流! --------------

1、HashMap对应泛型的使用

HashMap<String,Integer> maps =new HashMap<String,Integer>();

maps.put("lisi",23);

maps.put("wangwu",25);

maps.put("xiaoliu", 24);

Set<Map.Entry<String,Integer>>entrySet = maps.entrySet();

for(Map.Entry<String,Integer> entry :entrySet){

System.out.println(entry.getKey() + ":"+entry.getValue());

}

泛型的应用:

1、//1、编写一个泛型方法,自动将Object类型的对象转换成其他类型

Object obj = "abc";//1、

String x = autoConvert(obj);

private static<T> T autoConvert(Object obj) {//前面一个《T>是为了说明后面的T是泛型

return (T)obj;

}

2、//定义一个方法,可以将任意类型的数组中的所有元素填充为相应类型的某个对象。

private static<T> void fillArray(T arr[],Tobj){

for(int x=0;x<arr.length;x++){

arr[x] = obj;

}

}

3、通配符与自定义泛型方法的不同使用示例

//通配符的使用使用,?通配符可以引用其他各种参数化的类型,?通配符定义的变量主要用作引用,可以调用与参数化无关的方法,不能调用与参数化有关的方法。

public static void printCollection(Collection<?>collection){

System.out.println(collection.size());

for(Object obj : collection){

System.out.println(obj);

}

}

//采用自定泛型方法的方式打印出任意参数化类型的集合中的所有内容。

public static <T> voidprintCollection2(Collection<T> collection){

System.out.println(collection.size());

for(Object obj : collection){

System.out.println(obj);

}

}

4、泛型定义在类与泛型定义在方法上的区别

public class GenericDao<E> {

public void add(E x){

}

public E findById(int id){

return null;

}

publicclass GenericDao {

public <T> void add(T x){

}

public <T> T findById(int id){

return null;

}

}

泛型的反射使用示例

1、ArrayList<String> collection1 = new ArrayList();

//通过反射实现这句话collection1.add("abc");

Constructor<String>constructor1=String.class.getConstructor(StringBuffer.class);

constructor1.newInstance(new StringBuffer("abc"));

2、通过反射返货实际参数的类型-Date示例

public static void applyVector(Vector<Date> v1){

}

MethodapplyMethod = GenericTest.class.getMethod("applyVector",Vector.class);

ParameterizedType pType =(ParameterizedType)applyMethod.getGenericParameterTypes()[0];

System.out.println(pType.getRawType());//获取原始类型class java.util.Vector

System.out.println(pType.getActualTypeArguments()[0]);//返回表示此类型实际类型参数的 Type 对象的数组。class java.util.Date

------------- java培训、android培训、java博客、java学习型技术博客、期待与您交流! -------------


详情请查看:http://edu.csdn.net/heima/

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics