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

时间:2025-03-10 18:43:32
import ;
import ;
import ;
public class ReflectTest {
 
 public static void main(String[] args) throws Exception {
  Class clazz = ("TaskProvidePropsList");//这里的类名是全名。。有包的话要加上包名
  Object obj = ();
  Field[] fields = ();
  //写数据
  for(Field f : fields) {
   PropertyDescriptor pd = new PropertyDescriptor((), clazz);
   Method wM = ();//获得写方法
   (obj, 2);//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型
  }
  //读数据
  for(Field f : fields) {
   PropertyDescriptor pd = new PropertyDescriptor((), clazz);
   Method rM = ();//获得读方法
   Integer num = (Integer) (obj);//因为知道是int类型的属性,所以转换成integer就是了。。也可以不转换直接打印
   (num);
  }
 }
}