Java反射调用get方法和set方法

来源:互联网 发布:免费刷枪软件下载 编辑:程序博客网 时间:2024/05/17 00:54
import java.beans.PropertyDescriptor;import java.lang.reflect.Field;import java.lang.reflect.Method;public class ReflectTest {  public static void main(String[] args) throws Exception {  Class clazz = Class.forName("TaskProvidePropsList");//这里的类名是全名。。有包的话要加上包名  Object obj = clazz.newInstance();  Field[] fields = clazz.getDeclaredFields();  //写数据  for(Field f : fields) {   PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);   Method wM = pd.getWriteMethod();//获得写方法   wM.invoke(obj, 2);//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型  }  //读数据  for(Field f : fields) {   PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);   Method rM = pd.getReadMethod();//获得读方法   Integer num = (Integer) rM.invoke(obj);//因为知道是int类型的属性,所以转换成integer就是了。。也可以不转换直接打印   System.out.println(num);  } }}

原创粉丝点击