Java中获取set和get方法

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);}}

}

风景如何,其实并不重要。重要的是,你在我的身边。

Java中获取set和get方法

相关文章:

你感兴趣的文章:

标签云: