java泛型和反射的简单例子

来源:互联网 发布:机器视觉 知乎 编辑:程序博客网 时间:2024/05/18 01:46
public static void main(String[] args) {//实例化这个类,泛型的类型定义为string,参数给字符串,得到的该类型为string。fx<String> fx1 = new fx<String>("abc");fx1.showTypeName();//实例化这个类,泛型的类型定义为integer,参数给数字,得到的该类型为integer。fx<Integer> fx2 = new fx<Integer>(123);fx2.showTypeName();//将泛型的类放入这个实例fx<people> fx3 = new fx<people>(new people());fx3.showTypeName();}}//泛型,作用是在声明类时不指定变量的类型,根据实例化时的情况自动选择。//定义一个类,包含一个泛型的类型Tclass fx<T>{//定义一个类型暂时为T的成员变量private T t;//构造函数public fx(T t){this.t=t;}//获得T的类型名称public void showTypeName(){System.out.println("类型是:"+t.getClass().getName());//通过反射机制,获得类中的重要信息。Method[] m = t.getClass().getDeclaredMethods();//显示存入数组的方法名for(int i=0;i<m.length;i++){System.out.println("方法是:"+m[i].getName());}} }//定义做泛型的类class people{public void walk(){System.out.println("people can walk");}public void sleep(){System.out.println("people can sleep");}}

0 0
原创粉丝点击