黑马程序员--加强之泛型

-------android培训java培训、期待与您交流!     ---------- 

package cn.itcast.day2;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import cn.itcast.day1.ReflectPoint;

public class GenericTest
{

	/**
	 * @param args
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws IllegalArgumentException 
	 * @throws ClassNotFoundException 
	 */
	public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException
	{
		ArrayList collection1 = new ArrayList();
		collection1.add(1);
		collection1.add(2L);
		collection1.add("abc");
		int i = (Integer) collection1.get(0);
		//int i = (int) collection1.get(0);
		
		ArrayList<String> collection2 = new ArrayList<String>();
		//collection2.add(1); // is not applicable for the argument
		//collection2.add(2L);
		collection2.add("abc");
		String s = collection2.get(0);
		
		// new String(new StringBuffer("abc");
		//带泛型的反射
		Constructor<String> constructor1 = 
			String.class.getConstructor(StringBuffer.class);
		String str1 = constructor1.newInstance(new StringBuffer("abc"));
		System.out.println(str1.charAt(2));
		
		//Generic type retent at the source only.
		ArrayList<Integer> collection3 = new ArrayList<Integer>();
		System.out.println(collection3.getClass() == collection2.getClass());//true
		
		//collection3.add("abc") by reflect
		Method methodAdd = collection3.getClass().getMethod("add", Object.class);
		boolean retVal = (Boolean)methodAdd.invoke(collection3, "abc");
		System.out.println(retVal);
		Object str2 = collection3.get(0);
		System.out.println(str2);
		
		printCollection(collection3);
		printCollection2(collection3);
		
		//Class<? extends Number> x = Object.class.asSubclass(Number.class);//compile ok, but run err
		Class<? extends Number> x = Number.class.asSubclass(Number.class);//run ok
		Class<?> y;
		//Class<String> x1 = Class.forName("java.lang.String");//Compile err
		Class<?> x1 = Class.forName("java.lang.String");//Compile OK
		Class<String> x2 = (Class<String>) Class.forName("java.lang.String");//Compile OK
		
		HashMap<String,Integer> maps = new HashMap<String,Integer>();
		maps.put("a",28);
		maps.put("b",21);
		maps.put("c",38);
		
		Set<String> set = maps.keySet();
		for(String key : set)
		{
			System.out.println(key+":"+maps.get(key));
		}
		
		Set<Map.Entry<String, Integer>> entrySet = maps.entrySet();
		for(Map.Entry<String, Integer> entry: entrySet)
		{
			System.out.println(entry.getKey()+":"+entry.getValue());
		}
		
		//泛型应用
		add(3,5);
		Number x11 = add(3.5, 3); //在Number 范围内 double 与 int可相加
		Object x22 = add(3, "abc"); //在Object范围内int 与 String 相加
		
		swap(new String[]{"abc", "xyz", "whb"}, 1, 2);
		swap(new Integer[]{100, 300, 200}, 1, 2);
		
		Object obj = "abc";
		String str3 = autoConvertType(obj);
		
		//泛型推演
		copy1(new Vector<String>(), new String[10]);
		copy2(new Date[10], new String[10]);//!define one generic type is enough.
		//copy1(new Vector<Date>(), new String[10]);// err. not applicable for the argument
		
		//泛型在DAO中的应用
		GnericDAO<ReflectPoint> dao = new GnericDAO<ReflectPoint>();
		dao.add(new ReflectPoint(3, 5));
		//String e =  dao.findById(1); //type err can be prompted when compilling
		ReflectPoint e =  dao.findById(1);
		
		//Vector<Date> v1 = new Vector<Date>();
		Method applyMethod = GenericTest.class.getMethod("applyVector", Vector.class);
		Type[] types = applyMethod.getGenericParameterTypes();//得到方法上的类型定义,其中包含泛型
		for(Type type : types)
		{	
			if(type instanceof ParameterizedType)
			{
				ParameterizedType pType = (ParameterizedType)type;
				System.out.println(pType.getRawType());//this type is in the class file
				System.out.println(pType.getOwnerType());
				System.out.println(Arrays.toString(pType.getActualTypeArguments()));
			}
			System.out.println();
			System.out.println(type.getClass());
		}
		
		//HashMap<String,Date> h1 = new HashMap<String, Date>();
		//Class clazz1 = HashMap<String,Date>.class;//complie error
		Class clazz2 = HashMap.class;
		//Class clazz3 = ArrayList<String>.class;//complie error
		Class clazz4 = ArrayList.class;

		Method applyMethod2 = GenericTest.class
			.getMethod("applyVector2", HashMap.class, Integer.class, Object.class);
		Type[] types2 = applyMethod2.getGenericParameterTypes();//得到方法上的类型定义,其中包含泛型
		for(Type type : types2)
		{	
			System.out.println("<---------");
			if(type instanceof ParameterizedType)
			{
				ParameterizedType pType = (ParameterizedType)type;
				System.out.println("rawType:"+pType.getRawType());//this type is in the class file
				System.out.println("ownerType:"+pType.getOwnerType());
				System.out.println(Arrays.toString(pType.getActualTypeArguments()));
			}
			System.out.println("type class:"+type.getClass());
			System.out.println("----------->");
		}
		//parameterized arguments was stored in the Method Object.
		/*
		  <---------
			rawType:class java.util.HashMap
			ownerType:null
			[class java.lang.String, class java.util.Date]
			type class:class sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
			----------->
			<---------
			type class:class java.lang.Class
			----------->
			<---------
			type class:class sun.reflect.generics.reflectiveObjects.TypeVariableImpl
			----------->
		 */
		
	}
	
	public static  void applyVector(Vector<Date> v1)
	{
		
	}
	public static <T> void applyVector2(HashMap<String,Date> h, Integer i, T t)
	{
		
	}
	private static <T> void copy2(T[] dates, T[] strings)
	{
		
	}

	private static <T> void copy1(Vector<T> vector, T[] strings)
	{
		
	}

	private static <T> T autoConvertType(Object obj)
	{
		return (T)obj;
	}

	private static <T> void swap(T[] array, int i, int j)
	{
		T temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}

	private static <T> T add(T i, T j)//泛型定义要加《》,而使用则无须
	{
		return null;
	}

	private static void printCollection(Collection<?> collection3)//? denote type is unkonw
	{	
		/*T t = (T)new Object();
		collection.add(t);*/
		
		System.out.println(collection3.size());
		for(Object obj : collection3)
		{
			System.out.println(obj);
		}
	}
	private static <T> void printCollection2(Collection<T> collection)//? denote type is unkonw
	{	
		/*T t = (T)new Object();
		collection.add(t);*/
		
		System.out.println(collection.size());
		for(Object obj : collection)
		{
			System.out.println(obj);
		}
	}

}

-------android培训java培训、期待与您交流!     ---------- 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值