在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中判断字段是否被修改。