您的位置:首页 > 其它

获取对象中字段的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;}}

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