在Java中,可以使用以下幾種方法來判斷字段是否被修改:
public class MyClass {
private int myField;
private int initialFieldValue;
public int getMyField() {
return myField;
}
public void setMyField(int myField) {
if (initialFieldValue == 0) {
initialFieldValue = myField;
}
this.myField = myField;
}
public boolean isMyFieldModified() {
return initialFieldValue != myField;
}
}
public class MyClass {
private int myField;
private List<FieldModifiedListener> listeners = new ArrayList<>();
public int getMyField() {
return myField;
}
public void setMyField(int myField) {
this.myField = myField;
notifyListeners();
}
public void addFieldModifiedListener(FieldModifiedListener listener) {
listeners.add(listener);
}
public void notifyListeners() {
for (FieldModifiedListener listener : listeners) {
listener.onFieldModified(this);
}
}
}
public interface FieldModifiedListener {
void onFieldModified(MyClass myClass);
}
通過以上兩種方法,可以在Java中判斷字段是否被修改。