getter和setter怎么用_python setter

getter和setter怎么用_python setter有时候我们只知道一个对象的字段,我们想通过反射的方式将此字段赋值,可直接写反射又太浪费时间,还需要自己手动拼接方法名,而java为我们提供了一个很方便的类(PropertyDescriptor)来操作这一过程。使用很简单,直接看代码:代码importcom.pibgstar.demo.bean.User;importjava.beans.IntrospectionException…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

有时候我们只知道一个对象的字段,我们想通过反射的方式将此字段赋值,可直接写反射又太浪费时间,还需要自己手动拼接方法名,而java为我们提供了一个很方便的类(PropertyDescriptor)来操作这一过程。使用很简单,直接看代码:

代码

import com.pibgstar.demo.bean.User;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/** * @author pibigstar * @create 2018-12-03 18:36 * @desc **/
public class TestPropertyDescriptor { 
   

    public static void main(String[] args){ 
   
        TestPropertyDescriptor test = new TestPropertyDescriptor();
        User user = new User();
        user.setId("123");

        Object id = test.getAttribute("id", user);
        System.out.println("id:"+id.toString());

        test.setAttribute("name",user,"pibigstar");

        System.out.println(user);
    }

    /** * @Author:pibigstar * @Description: 根据字段获取属性值 */
    private Object getAttribute(String filed,Object obj) { 
   
        try { 
   
            PropertyDescriptor pd = new PropertyDescriptor(filed,obj.getClass());
            // 获取getter方法
            Method method = pd.getReadMethod();
            Object result = method.invoke(obj);
            return result;
        } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) { 
   
            e.printStackTrace();
        }
      return null;
    }

    /** * @Author:pibigstar * @Description: 设置属性字段值 */
    private void setAttribute(String filed,Object obj,Object value) { 
   
        try { 
   
            PropertyDescriptor pd = new PropertyDescriptor(filed,obj.getClass());
            // 获取setter方法
            Method method = pd.getWriteMethod();
            method.invoke(obj, value);
        } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) { 
   
            e.printStackTrace();
        }
    }
}

User对象也放一下吧

public class User { 
   
    private String id;
    private String name;
   // setter/getter 方法
}

运行结果

id:123
User{id='123', name='pibigstar'}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/187273.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号