时间:3/5 3:30pm 地点:教室
现在的状态确实是有点差,教室里空调的高温弄得我头痛,也许是缺少新鲜空气!出去转了几圈,想清醒一下大脑,回到座位上以后稍微好点,有点窒息的感觉,无法深入思考。待会我一定要换换位置,不然这也太难受了。
一、反射机制的概念
指在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法,对于任意一个对象,都能调用它的任意一个方法.这种动态获取信息,以及动态调用对象方法的功能叫java语言的反射机制。
二、反射机制的实现
import java.lang.reflect.Method;
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Gen<Bird> gen = new Gen<Bird>(new Bird());
gen.showType();
// System.out.println("o=="+(gen.getData()));
}
}
class Bird{
private int a=5;
public int count(int a,int b){
return (a+b);
}
public void test(){
System.out.println("This is just a test!");
}
}
class Gen<T>{
private T o;
public Gen(T a){
o=a;
}
//泛型方法
public T getData(){
return o;
}
//显示o的类型
public void showType(){
System.out.println("类型是:"+o.getClass().getName());
Method [] m=o.getClass().getDeclaredMethods();
for(int i=0;i<m.length;i++){
System.out.println(m[i].getName());
}
}
}
输出
类型是:demo.Bird
count
test
以上代码中可以看出,由于它变量O的类型是泛型,所以通过O这个变量查询到了:
包名.类名 demo.Bird
类方法名:count ,test