引用传递比较常见,下面是无效的几个示例
public class Test {
public static void main(String[] args) {
Test test = new Test();
// 传null,不管怎么变,结果还是null
test.test1();
}
public void test1() {
TestPojo testPojo = null;
setTestPojo(testPojo);// 调用
System.out.println(JSON.toJSONString(testPojo));// null
}
public void setTestPojo(TestPojo testPojo) {
testPojo = TestPojo.builder()
.name("新的")
.build();
}
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TestPojo {
private String name;
}
public class Test {
public static void main(String[] args) {
Test test = new Test();
// 传obj,new后
test.test2();
}
public void test2() {
TestPojo testPojo = TestPojo.builder()
.name("原来的")
.build();
setTestPojo(testPojo);// 调用
System.out.println(JSON.toJSONString(testPojo));// {"name":"原来的"}
}
public void setTestPojo(TestPojo testPojo) {
testPojo = TestPojo.builder()
.name("新的")
.build();
}
}
public class Test {
public static void main(String[] args) {
Test test = new Test();
// 传obj,设null
test.test3();
}
public void test3() {
TestPojo testPojo = TestPojo.builder()
.name("原来的")
.build();
setTestPojoNull(testPojo);// 调用
System.out.println(JSON.toJSONString(testPojo));// {"name":"改原来的"}
}
public void setTestPojoNull(TestPojo testPojo) {
testPojo.setName("改原来的");
testPojo = null;
}
}