[英]Change object fields after object creation in java
I have 3 class First, Second, and Third, Third class has a field name, I am creating an object of three classes, Now after the creation of the object I want to change the name of the Third class field from "john" to "sam", How can I update that without creating a new Third class object. I have 3 class First, Second, and Third, Third class has a field name, I am creating an object of three classes, Now after the creation of the object I want to change the name of the Third class field from "john" to “山姆”,如何在不创建新的第三个 class object 的情况下更新它。
public class First {
List<Second> second;
public List<Second> getSecond() {
return second;
}
public void setSecond(List<Second> second) {
this.second = second;
}
}
Second第二
public class Second {
protected Third third;
public Third getThird() {
return third;
}
public void setThird(Third third) {
this.third = third;
}
}
Third第三
public class Third {
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Third{" +
"name='" + name + '\'' +
'}';
}
}
Test测试
public class Test {
public static void main(String[] args) {
Third third = new Third();
third.setName("john");
Second second = new Second();
List<Second> list = new ArrayList<>();
list.add(second);
second.setThird(third);
First first = new First();
first.setSecond(list);
// How can I set change Third object name from john to Sam
System.out.println(first.second.get(0).third.toString());
}
}
When you have instance of First
class, then you can use getter to get required object and then use it to the the field:当您有
First
class 的实例时,您可以使用 getter 获取所需的 object,然后将其用于该字段:
first.getSecond().get(0).getThird().setName("Sam");
PS This is not safe, because you can get NPE
or eg second
list could be empty. PS这是不安全的,因为你可以得到
NPE
或者second
列表可能是空的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.