java类型属性set方法无法被赋值

前言

遇到一个基础的问题 方法设置属性值 失败

问题代码

有个内部类的User对象 分别使用 方式一和 方式二 设置User的属性值 发现方式一的属性并不能被设置成功 可以自行测试下

java 复制代码
public class Test{
    public static void main(String[] args) {
		#方式一 
        User user= new User();
        user.setName("123");
        log.info("user:{}",user.getName());

        #方式二
        User user2= new User()
                .setName("123");
        
        log.info("user2:{}",user2.getName());
        
    }


    @AllArgsConstructor
    @NoArgsConstructor
    static class User{
        private String name;

        public String getName() {
            return name;
        }

        public User setName(String name){
            return new User(name);
        }
    }

}

解决

由于使用@data这种方式的注解过多 导致遇到这种 直接返回this的 设置属性方式 慢慢忘却了。

方式一的正确赋值方式

java 复制代码
#方式一 
User user= new User();
user = user.setName("123");
log.info("user:{}",user.getName());

或者直接使用Builder 来创建对象

相关推荐
文丑颜不良啊34 分钟前
LeetCode3281~3300题目解析
java·leetcode
nice_lcj5202 小时前
【从零理解计算机网络 · 02】分层模型:别背 OSI 七层,看数据怎么被“打包“和“拆包“
java·后端·tcp/ip·计算机网络·面试·osi·分层模型
SimonKing2 小时前
给Deepseek Harness装上插件市场,从此插件无忧
java·后端·程序员
艾莉丝努力练剑3 小时前
【AI大模型接入SDK】C++的SessionManager 线程安全
java·开发语言·前端·c++·人工智能·学习·安全
aiotto资源分享3 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
RuoyiOffice4 小时前
SpringBoot3+Vue3 采购到付款:ERP、WMS与财务如何按同一来源协同
java·spring boot·架构·vue
文丑颜不良啊4 小时前
LeetCode3261~3280题目解析
java·leetcode
代码不停4 小时前
Spring 原理
java·spring
企业数字化笔记5 小时前
报表上线怎么对账?口径回归、权限抽检与差异定位
java·spring boot·mysql
乌暮5 小时前
少写重复 CRUD:用大白话搞懂 MyBatis-Plus
java·开发语言·spring boot·面试·mybatis