Java 泛型和通配符

Java 泛型和通配符

       很多时候,反射并不能满足业务的需求,Java 泛型和通配符与反射配合使用可使得反射的作用发挥到完美的地步,从而实现真正的通用。

直接上代码


import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通配符基于泛型,用来修饰泛型
 * 通配符和泛型都是用来声明类型的
 */
public class GenericityClass<T> {
	
	public static void main(String[] args) {
		System.out.println(test(new Pojo<Integer>()));

		new GenericityClass<Comparable<?>>().test4(new ArrayList<Integer>());
		new GenericityClass<Integer>().test5(new ArrayList<Comparable<?>>());
		List<?>[] l = new GenericityClass<Integer>().test6(1);
		System.out.println(l[0].get(0));
		System.out.println(l[1].get(0));
	}
	
	/**
	 * 泛型
	 */
	public static <T extends Comparable<? super Integer> & Serializable> T test(T t) {
		return t;
	}
	
	/**
	 * 通配符
	 */
	public Integer test2(Pojo<? extends Comparable<Integer>> t) {
		return 1;
	}

	/**
	 * 通配符
	 */
	public Integer test3(Pojo<? super Serializable> t) {
		return 1;
	}

	/**
	 * 通配符 extends 和 super
	 */
	public void test4(List<? extends T> set) {}
	public void test5(List<? super Integer> set) {}

	/**
	 * 通配符数组
	 */
	public List<?>[] test6(T t) {
		List<?>[] arr = new ArrayList<?>[2];
		List<Integer> l1 = new ArrayList<Integer>();
		l1.add(1);
		List<Object> l2 = new ArrayList<Object>();
		l2.add(new Object());
		arr[0] = l1;
		arr[1] = l2;
		return arr;
	}
}

实体类代码


class Pojo<T> implements Comparable<Integer>, Serializable{
	private static final long serialVersionUID = 1L;
	private String name;
	private Integer id;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Override
	public int compareTo(Integer o) {
		return 0;
	}
}

泛型擦除

       在很多书籍中能见到泛型擦除这几个字眼儿,但是在Java7以后,泛型擦除引发的各种问题基本已被解决。

代码:


/**
 * 泛型擦除:如List<T> 在javac编译后T将被擦除掉,并在相应的地方插入强制转换类型代码
 */
class Example {
	public static void main(String[] args) {
		test1();
		test2();
	}
	/**
	 * 泛型擦除前示例
	 */
	public static void test1() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("hello", "你好");
		map.put("how are you?", "吃了没?");
		System.out.println(map.get("hello"));
		System.out.println(map.get("how are you?"));
	}
	/**
	 * 泛型擦除后示例
	 */
	public static void test2() {
		Map map = new HashMap();
		map.put("hello", "你好");
		map.put("how are you?", "吃了没?");
		System.out.println((String) map.get("hello"));
		System.out.println((String) map.get("how are you?"));
	}
}

输出的结果并没有差异

猜你喜欢

转载自blog.csdn.net/weixin_37481769/article/details/84260369
今日推荐