获取对象中字段的get和set方法
2014-12-19 16:47
591 查看
import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * wangjian 2014-12-19 下午3:57:13 */ public class GetAndSetMethod { public GetAndSetMethod() { } public static void main(String[] args) { method(new Course()); } public static void method(Object obj) { try { Class<? extends Object> clazz = obj.getClass(); Field[] fields = obj.getClass().getDeclaredFields();// 获得属性 for (Field field : fields) { System.out.println(field.getName()); try { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz); // getMethod Method getMethod = pd.getReadMethod();// 获得get方法 if (getMethod != null) { System.out.println("getMethod = " + getMethod.getName()); // Object o = getMethod.invoke(obj);//执行get方法返回一个Object } // setMethod Method setMethod = pd.getWriteMethod(); if (setMethod != null) { System.out.println("setMethod = " + setMethod.getName()); } System.out.println("字段"+field.getName() + ": has get and set method"); } catch (Exception e) { // 字段没有get或set方法时抛出异常 continue;<pre name="code" class="java"><span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"> </span> }</span>} } catch (Exception e) { e.printStackTrace(); } }}
// 实体类
<pre name="code" class="java">public class Course {private long id;private String name;// public long getId() {// return id;// }public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
相关文章推荐
- 面向对象之get、set和直接获取public字段的区别?
- java反射通过字段名获取set、get方法
- 获取表单对象,得三种方法getElementById(), getElementsByName(), and getElementsByTagName() 和用法
- 非静态的字段、方法或属性“System.Web.UI.Page.Session.get”要求对象引用
- objective-c中对象所有权的内存管理(关于set,get方法),以及如何使用@property来进行简易操作(九)
- java中获取实体类中的get、set方法名
- 获取表单对象,得三种方法getElementById(), getElementsByName(), and getElementsByTagName() 和用法
- 反射获取对象成员的字段值,getFields()和getDeclaredFields()用法区别
- 获取表单对象,得三种方法getElementById(), getElementsByName(), and getElementsByTagName() 和用法
- 转:java中获取实体类中的get、set方法名
- 转:java中获取实体类中的get、set方法名
- EasyUI treegrid 获取编辑状态中某字段的值 [getEditor方法获取不到editor]
- 获取表单对象,得三种方法getElementById(), getElementsByName(), and getElementsByTagName() 和用法
- 获取表单对象,得三种方法getElementById(), getElementsByName(), and getElementsByTagName() 和用法
- C#反射新建类实例和调用类方法及属性帮助类 以及获取或设置对象属性中字段值帮助类
- JS 实现对象属性的get 和set方法
- NetBox环境下ajax用get获取数据,中文乱码的问题解决:对象不支持此属性或方法: 'Response.CharSet'
- structs2:action如何从页面获取参数值以及如何向页面传出参数值(set方法 、get方法、getParameters()方法
- [转]Eclipse get/set方法自动加上字段注释
- 获取表单对象,得三种方法getElementById(), getElementsByName(), and getElementsByTagName() 和用法