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 dl = new ArrayList();dl.add(dog1);Dog d = dl.get(0);//Cat c = dl.get(0);这样的编译是不通过的//java反射机制Gen gs = new Gen("aaa");gs.showTypeName();Gen myb = new Gen(new Bird());myb.showTypeName();}}//当我们不确定T的类型时,就用泛型代替,并且能减少重复代码,提高效率class Gen{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. 链接器解析多重定义的全局变量
  2. ubuntu NDK 的安装
  3. Android(安卓)编译NDK
  4. 【【【常用的ubuntu第三方工具及android命令(自存档)】】】二
  5. CyanogenMod 编译 Google Galaxy Nexus (GSM) 全过程
  6. 在android平台上编译libpcap-0.9.8 和 jnetpcap-1.2.rc1
  7. 在android平台上编译libpcap-0.9.8 和 jnetpcap-1.2.rc1
  8. 使用Android(安卓)Instrument 自动测试 WIFI_SERVICE
  9. android Uri获取真实路径转换成File的方法

随机推荐

  1. 【工作总结】一键清理总结
  2. android 5种布局
  3. 最全最好用的Android Studio插件整理
  4. Android(安卓)SlidingMenu侧滑菜单使用介
  5. Android Studio使用中遇到的问题
  6. Android答题app
  7. Android移动热修复--Sophix
  8. Android 异常捕获最少必要知识
  9. Android train——基本组件LinearLayout
  10. android AIDL简单步骤