首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

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

2013-01-28 
Android开发从零开始之java-泛型初步package testimport java.lang.reflect.Methodimport java.util.Arr

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;}

热点排行