Java泛型的作用是限制参数的类型,避免强转可能导致的错误,常见的写法包括 T、? extends T、? super T。泛型修饰的地方包括方法参数、类(构造方法参数)、方法返回类型。代码演示:
父类:
public abstract class C {
public C(String inf) {
this.inf = inf;
}
public abstract String output();
protected String inf;
}
子类C1
public class C1 extends C {
public C1(String inf) {
super(inf);
}
@Override
public String output() {
return "C1: " + inf;
}
}
子类C2:
public class C2 extends C {
public C2(String inf) {
super(inf);
}
@Override
public String output() {
return "C2: " + inf;
}
}
泛型类:
public class Template<T extends C> {
private T t;
public Template(T t) {
this.t = t;
}
public String output() {
return t.output() + "\"" + t.getClass().getName() + "\"";
}
}
public class Main {
public static final String inf = "The class name is ";
public static void main(String[] args) {
Template<C1> tc1 = build(C1.class);
System.out.println(tc1.output());
Template<C2> tc2 = build(C2.class);
System.out.println(tc2.output());
Template<C3> tc3 = build(C3.class);
System.out.println(tc3.output());
//期望输出
/*
C1: The class name is "com.btt.test.C1"
C2: The class name is "com.btt.test.C2"
C3: The class name is "com.btt.test.C3"
*/
}
}
要求:
- 输入为Class对象(可能是C1/C2/C3)
- 返回Template泛型对象,要求返回的泛型参数对应输入的Class对象
- 注意:再构造Template对象时先要实例化Class对象(C1/C2/C3其构造方法需要的参数请使用Main.inf).
泛型实现:
private static <T extends C> Template<T> build(Class<T> clazz) {
Template<T> temp = null;
Constructor<T> constructor = null;
try {
constructor = clazz.getConstructor(String.class);
temp = new Template<T>(constructor.newInstance(Main.inf));
} catch (Exception e) {
e.printStackTrace();
}
return temp;
}
转载请标明出处:http://blog.youkuaiyun.com/tpxwantpxwan/article/details/38823121