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

Java 反射机制获取Class中的方法 和字段

2017-10-30 12:32 441 查看
package p1.reflect.demo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import itcast.bean.Person;

public class ReflectDemo4 {

public static void main(String[] args) throws Exception {
getMethodDemo_3();

}
private static void getMethodDemo_3() throws Exception {
Class clazz=Class.forName("itcast.bean.Person");
Method method=clazz.getMethod("paramMethod",String.class,int.class);//传入 返回值类型
Object obj=clazz.newInstance();//新建一个对象
method.invoke(obj, "小强",89);//调用获取到的方法
}
private static void getMethodDemo_2() throws Exception {
Class clazz=Class.forName("itcast.bean.Person");
Method method=clazz.getMethod("show", null);//获取空参数一般方法

//Object obj=clazz.newInstance();
Constructor constructor=clazz.getConstructor(String.class,int.class);
Object obj=constructor.newInstance("小明",22);
method.invoke(obj, null);

}
/*
* 获取指定Class中的公共函数
*/
public static void getMethodDemo() throws Exception {
Class clazz=Class.forName("itcast.bean.Person");
//Method[]methods=  clazz.getMethods();//获取的都是共有的方法
Method[]methods=clazz.getDeclaredMethods();//只获取本类中所有方法 包含私有
for(Method method:methods) {
System.out.println(method);
}
}

}


package p1.reflect.demo;

import java.io.File;
import java.lang.reflect.Field;

public class ReflectDemo3 {

public static void main(String[] args) throws Exception, NoSuchFieldException, SecurityException {
getFieldDemo();
}

/*
* 获取字节码中的字段
*/
private static void getFieldDemo() throws ClassNotFoundException, NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
Class clazz=Class.forName("itcast.bean.Person");

//Field file= clazz.getField("age");//只能获取公共的(public) 凡是带declare的可以获取类中所有内容(共有 私有都ok)
Field field=clazz.getDeclaredField("age");

//对私有字段的访问取消权限检查 暴力访问
field.setAccessible(true);

Object obj=clazz.newInstance();

field.set(obj, 89);

Object o= field.get(obj);

System.out.println(o);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐