您不想更改原始引脚值,您需要它,对吧?然后你应该使用 toString 方法。修改您的 GiftCard 类。请参阅下面的代码和其中的 cmets。实际上那里的 cmets 比 code 多:
public class GiftCard implements Cloneable {
Map<String, Object> extendedProperties;
String expiryDate;
double originalAmount;
String cardNumber;
@Override
protected Object clone() throws CloneNotSupportedException {
GiftCard cloned = (GiftCard)super.clone();
// the default behavior of clone() is to return a shallow copy of the object.
// This means that the values of all of the original object’s fields are copied to the fields of the new object.
// If the fields are primitive types, the changes made to this object will not be reflected to cloned ones.
// But if the fields are not primitive, only their references are cloned,
// which means any change on that fields, are applied to original and the cloned objects.
// So here we have to get a copy of your hash map.
cloned.extendedProperties = new HashMap<String, Object>(this.extendedProperties);
return cloned;
}
@Override
public String toString() {
try {
GiftCard giftCardToPrint = null;
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
if(this.extendedProperties != null && this.extendedProperties.get("pin") != null) {
// You don't want to change the original pin value so clone original instance, see clone method.
giftCardToPrint = (GiftCard) this.clone();
giftCardToPrint.extendedProperties.put("pin", "*");
} else {
giftCardToPrint = this;
}
return gson.toJson(giftCardToPrint);
} catch (Exception e) {
e.printStackTrace();
return super.toString();
}
}
}
试试下面的代码:
System.out.println("giftCard toString:" + giftCard.toString());
System.out.println("giftCard toJson :" + gson.toJson(giftCard));
System.out.println("giftCard.pin :" + giftCard.extendedProperties.get("pin"));
输出:
giftCard toString:{"cardNumber":"1111 2222 3333 4444","extendedProperties":{"pin":"*"},"originalAmount":0.0}
giftCard toJson :{"cardNumber":"1111 2222 3333 4444","extendedProperties":{"pin":"1234"},"originalAmount":0.0}
giftCard.pin :1234