Java取得一个对象里所有get方法和set方法

public void getMethod(Object obj){  
    Class clazz=obj.getClass();//获得实体类名  
    Field[] fields = obj.getClass().getDeclaredFields();//获得属性  
    //获得Object对象中的所有方法  
    for(Field field:fields){  
        PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);  
        Method getMethod = pd.getReadMethod();//获得get方法  
        getMethod.invoke(obj);//此处为执行该Object对象的get方法  
        Method setMethod = pd.getWriteMethod();//获得set方法      
        setMethod.invoke(obj,"参数");//此处为执行该Object对象的set方法  
    }  
} 

注意:

Field所属的包为java.lang.reflect.Field;

PropertyDescriptor所属的包为java.beans.PropertyDescriptor;

Method 所属的包为java.lang.reflect.Method;

set方法中参数有几个就要在invoke中添加几个,保证与你的对象的set方法格式一致。


猜你喜欢

转载自blog.csdn.net/weixin_37962025/article/details/80778528
今日推荐