现在的位置: 首页 > 综合 > 正文

java 之 泛型学习示例

2014年02月17日 ⁄ 综合 ⁄ 共 2237字 ⁄ 字号 评论关闭
import java.util.Collection;


public class GenericTest {

	/**
	 * T 
	 * 类型推断:
	 * 1.多个参数,不同的类型,又没有返回值,取最大交集
	 *2. 如果有返回值,则根据返回值
	 * Number x1 = add(2.3,2);
	 * Object x2 = add(3,"abc");
	 * 会取最小公倍数
	 * 
	 * <T> 说明类型
	 * @param args
	 */
	public static void main(String[] args) {
		Object obj = "abc";
		String str = autoConvertType(obj);
	}
	
	//根据返回值类型确定T
	public static <T> T autoConvertType(Object obj) {
		return (T)obj;
	}
	
	private static <T> void fillArray(T[] dest, T obj) {
		for(int i=0;i<dest.length;i++) {
			dest[i] = obj;
		}
	}
	
	private static <T> void swap(T[] a, int i, int j) {
		T tmp = a[i];
		a[i] = a[j];
		a[j] = tmp;
	}
	
	private static <T> T add(T x, T y) {
		return null;
	}
	
	//通配符比T高效,但是操作有限,比如不能使用add(),类型不确定,编译通不过
	public static void printCollection(Collection<?> collection) {
		System.out.println(collection.size());
		for(Object obj:collection) {
			System.out.println(obj);
		}
	}
	
	public static <T> void printCollection2(Collection <T> collection, T arg) {
		System.out.println(collection.size());
		for(Object obj:collection) {
			System.out.println(obj);
		}
		
		//可以通过
		collection.add(arg);
		
	}
	
	public static <T> void copy1(Collection<T> dest, T[] src) {
		
	}
	
	public static <T> void copy2(T[] dest, T[] src) {
		
	}
}
import java.util.Set;


/**
 * 把T定义到类上,类级别的泛型,统一方法的泛型类型
 * 有多个方法使用泛型,使用类级别的泛型
 * @author ETHAN
 *
 *GenericDao<E>
 *
 *GenericDao<Person> dao = new GenericDao<Person>();
 *
 *编译过后,泛型就被编译器×除了,去掉了
 *上边的没法得到泛型参数类型
 *但可以通过方法中的参数(采用了泛型),获取泛型
 * @param <T>
 */
public class GenericDao<T> {
	public void add(T obj) {
		
	}
	
	public T findById(int id) {
		return null;
	}
	
	public void delete(int id) {
		
	}
	
	public void delete(T obj) {
		
	}
	
	public void update(T obj) {
		
	}
	
	//静态方法,独立泛型
	public static <T> void update2(T obj) {
		
	}

	public T findByUserName(String name) {
		return null;
	}
	
	public Set<T> findByConditions(String where) {
		return null;
	}
}

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.Vector;


public class ReflectGenericTest {

	/**
	 * 通过反射获得泛型的实际类型参数
	 */
	public static void main(String[] args) throws Exception {
		Method applyMethod = ReflectGenericTest.class.getMethod("applyVector", Vector.class);
		Type[] types = applyMethod.getGenericParameterTypes();
		
		//参数化类型
		ParameterizedType pType = (ParameterizedType) types[0];
		System.out.println(pType.getRawType());
		//HashMap<K,V>多个
		System.out.println(pType.getActualTypeArguments()[0]);
		
		/*
		 * 打印结果:
		 * class java.util.Vector
			class java.util.Date
			这样就获得了Vector里边的类型
		 */
	}

	public static void applyVector(Vector<Date> v1) {
		
	}
	
/*	下边的不是重载,编译后就会去掉泛型
 * public static void applyVector(Vector<Integer> v1) {
		
	}*/
}

抱歉!评论已关闭.