您的位置:首页 > 编程语言 > Java开发

Java-反射

2017-01-03 23:57 113 查看

任何一个类都是Class的实例对象,这个实例对象有三种表示方式

//第一种,任何一个类都有一个隐含的静态成员变量
Class c1 = Foo.class;
//第二种,已知该类的对象通过getClass方法获取
Class c2 = foo1.getClass();
//第三种
Class c3 = Class.forName("com.uds.flect.Foo");
//很明显 c1是等于c2以及等于c3的

//我们可以通过c1,c2,c3来创建Foo的对象
Foo foo = (Foo)c1.newInstance();


获取方法

Method[] method = c.getMethods();

Class returnType = method[0].getReturnType();
Class[] parameterType = method[0].getParameterTypes();

method[0].invoke(c);//没有参数的话  有的话可以使xx.class,yy.class或者数组new Class[]{xx.class,yy.class}有几个就几个 没有就不写
//遍历


获取属性

Field[] field = c.getFields();
Class type = field[0].getType();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: