空接口
给实现该接口的类做一个标识,然后通过该标识对类做统一处理。
举例如下:
package exc;
//里面包含Person信息,但信息分为两类,
//一类是基本信息,一类是联系信息
//限制该泛型只能使用BasicInfo和MsgInfo
//当以后遇到不同类的公共问题?向上提取
//向上提取,做成超类Info
public class Person {
private T msg;
public T getMsg() {
return msg;
}
public void setMsg(T msg) {
this.msg = msg;
}
@Override
public String toString() {
return "Person [msg=" + msg + "]";
}
}
package exc;
//包含Person的基本信息
public class BasicInfo implements Info {
private T name;
public T getName() {
return name;
}
public void setName(T name) {
this.name = name;
}
@Override
public String toString() {
return "BasicInfo [name=" + name + "]";
}
}
// 联系信息
class MsgInfo implements Info {
private T msg;
public T getMsg() {
return msg;
}
public void setMsg(T msg) {
this.msg = msg;
}
@Override
public String toString() {
return "BasicInfo [name=" + msg + "]";
}
}
package exc;
public class Test {
public static void main(String[] args) {
// 泛型嵌套
Person<BasicInfo> p = new Person();
BasicInfo<String> basic = new BasicInfo<>();
basic.setName("张三");
p.setMsg(basic);
System.out.println(p);
Person<MsgInfo<String>> p2 = new Person();
MsgInfo<String> msgInfo = new MsgInfo<>();
msgInfo.setMsg("1234567");
p2.setMsg(msgInfo);
System.out.println(p2);
// 基本信息,还是联系信息?
// Person<String> p3 = new Person();
// p3.setMsg("hello world");
// System.out.println(p3);
}
}
通过定义一个标识接口来实现限制泛型上限
package exc;
public interface Info {// 标识接口
// 没有定义具体规范
}