首页 > 代码库 > 获取对象中字段的get和set方法

获取对象中字段的get和set方法

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方法