Android开发从零开始之java-泛型初步

package test;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/*
 * 作者:钟志钢
 * 功能:泛型
 * 时间:2013-1-27
 * 1, 泛型好处:类型安全,向后兼容,层次清楚,性能较高
 */
public class 泛型 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		泛型 fx = new 泛型();
	}
	public 泛型(){
		List al = new ArrayList();
		Dog dog1 = new Dog();
		al.add(dog1);
		Dog dog = (Dog) al.get(0);//正确
		//当我们不知道al里装的是什么,如果
		//Cat cat = (Cat) al.get(0);//编译可能通过,运行不会通过,发生运行时错误
		
		//解决方案:泛型,这样可以把错误发生的可能提前到编译时
		List<Dog> dl = new ArrayList<Dog>();
		dl.add(dog1);
		Dog d = dl.get(0);
		//Cat c = dl.get(0);这样的编译是不通过的
		
		//java反射机制
		Gen<String> gs = new Gen<String>("aaa");
		gs.showTypeName();
		
		Gen<Bird> myb = new Gen<Bird>(new Bird());
		myb.showTypeName();
	}
}
//当我们不确定T的类型时,就用泛型代替,并且能减少重复代码,提高效率
class Gen<T>{
	private T o;
	public Gen (T a){
		this.o = a;
	}
	public void showTypeName(){
		System.out.println("o 的类型是:" + o.getClass().getName());
		//通过反射机制可以得到T类型的很多信息,比如成员函数
		Method [] ms = o.getClass().getDeclaredMethods();//获得所有public方法
		for(Method m : ms){
			System.out.println(m.getName());
		}
	}
}
class Bird {
	public void test1(){
		System.out.println("bird");
	}
	public void count (int a , int b){
		System.out.println("Bird计算a+b" + (a + b));
	}
}
class Dog {
	private String name ; 
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	private int age;
	
}
class Cat {
	private String color;
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	private int age;
	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值