Java 泛型与类型擦除

下面是一个简单的 Java 泛型例子:

public static void main(String[] args) {
	Map map = new HashMap();
	map.put("hello", "你好");
	System.out.println(map.get("hello"));
}

泛型擦除后:

public static void main(String[] args) {
	Map map = new HashMap();
	map.put("hello", "你好");
	System.out.println((String) map.get("hello"));
}

//////

先看一个问题代码:

public class Manipulation {
	public static void main(String[] args) {
		HasF hf = new HasF();
		Manipulator m = new Manipulator<>(hf);
		m.manipulate();
	}
}

class HasF {
	public void f() {
		System.out.println("HasF.f()");
	}
}

class Manipulator {
	private T obj;
	public Manipulator(T x) {
		obj = x;
	}
	public void manipulate() {
		obj.f(); /* 编译器无法知道你拥有 f() 方法 */
	}
}

在 Manipulator 类中,Java 编译器无法知道 obj 对象拥有 f() 方法,必须给定泛型类边界,以此告知编译器只能接收遵循这个边界的类型。这里重用了 extends 关键字。由于有了边界,下面的代码就可以编译了:

class Manipulator {
	private T obj;
	public Manipulator(T x) {
		obj = x;
	}
	public void manipulate() {
		obj.f(); /* 编译可以通过了 */
	}
}

 

你可能感兴趣的:(JavaSE)