Java泛型的高级应用

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() + "\"";
	}
}


应用Demo, 请实现build方法(static)

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"
		*/
	}
}

要求:

  1. 输入为Class对象(可能是C1/C2/C3)
  2. 返回Template泛型对象,要求返回的泛型参数对应输入的Class对象
  3. 注意:再构造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.csdn.net/tpxwantpxwan/article/details/38823121

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值