
Question:
I don't have a better title for this question, you may help me change it.
class Example {
class A {
private String str;
public String getStr() {
return str==null ? "nothing" : str;
}
public void setStr(String str) {
this.str = str;
}
}
public static void main(String[] args) {
A a = null;
loadA(a);
System.out.println(a.getStr());
}
private static void loadA(A a) {
// a = ****;
// in my project, a is load from a json string using Gson
// Gson cannot modify a Object, it can only create a new one, say b
// I tried to copy every field from b to a
// but the method getStr do not always return the true str
// so I may have to create another method "getTrueStr()" which feels bad
}
}
Considered solutions and problems:
<ol><li>a = Gson.createAnotherA()
</li>
</ol>It doesn't work.
<ol><li>I tried to copy every field from b to a</li> </ol>but the method getStr()
do not always return the true str, so I may have to create another method getTrueStr()
which make me feel bad.
clone()
</li>
</ol>make me feel even worse.
<ol start="3"><li>a = loadA(a)
;</li>
</ol>this one is good. But I don't very like it. Because I have other loadB()
, loadC()
and they don't need this syntax, and it will look just inharmonious. If no better solution comes up, I'd choose this one.
Question is, what can I do if I choose none of my given solution.
or
If I am given a reference A a
in a method, how can I make it the same to another Object while not using clone()
and what I wrote above.
I think your problem really lies in your getStr
method, which is not a real getter, it contains some logic. Is it possible to handle this outside class A
?
As far as I understand, you want to create object b
(of type A
), which is copy of existing instance a
.
Because a
is loaded from JSON, you could just read the JSON again, which should create a new instance. I guess for some reason you cannot do this.
Instead of using JSON serializer or clone
method (which shouldn't be used at all - it has multiple flaws), you could create a "copy-constructor":
class A {
private String str;
public A() {}
public A(A that) {
this.str = that.str;
}
public String getStr() {
return str==null ? "nothing" : str;
}
public void setStr(String str) {
this.str = str;
}
}
Answer2:I came out with this. Perfectly satisfied my need and looks nice.
class A {
private A reference;
private String name;
public A() {
reference = this;
}
public void setReference(A ref) {
reference = ref;
}
public void setName(String name) {
reference.name = name;
}
public String getName() {
return reference.name;
}
}