potete trovare una domanda molto simile qui con abbastanza buona spiegazione:
QUI: Why can final object be modified?
Tra l'altro ho iniziato a pensare a meccanismi di riflessione ....
in teoria .. .Credo che tu possa ottenere l'istanza di classe proprietaria .. quindi ottenere membri della classe, trovare istanza corrente e controllare che sia definitiva ....
Non l'ho controllato e non ho nemmeno kwnow se è possi BLE - è solo un'idea (? forse)
in
public class Final {
static final Point p = new Point();
public static void main(String[] args) throws MyImmutableException {
p = new Point(); // Fails
p.setB(10); // OK
p.setA(20); // Fails - throws MyImmutableException
}
}
public class Point() {
int a = 10;
int b = 20;
public setA(int a) {
this.a = a;
}
public setB(int b) throws MyImmutableException {
detectIsFinal()
this.b = b;
}
private void detectIsFinal() throws MyImmutableException {
int mod = this.getClass().getModifiers()
if (Modifier.isFinal(mod)) {
throw new MyImmutableException();
}
}
}
public class MyImmutableException extends Exception {
public MyImmutableException() {super(); }
}
pensavo che altro si può fare ... ancora una volta è solo un !!!!!!!!! PSEUDOCODE !!! Non sono sicuro che funzionerà anche: P
Forse qualcuno con conoscenza delle annotazioni sarà ispirato e farlo funzionare. Purtroppo non ho più tempo questa settimana. Forse più tardi cercherò di creare un POC.
public class Final {
@Immutable
static final Point p = new Point();
public static void main(String[] args) {
p = new Point(); // Fails
p.setB(10); // Fails
p.setA(20); // OK
}
}
public class Point() {
int a = 10;
@ImmutableOnThisInstance
int b = 20;
@DetectIsImmutable
public setA(int a) {
this.a = a;
}
@DetectIsImmutable
public setB(int b) {
this.b = b;
}
}
class Immutable {
?????????????????
}
class DetectIsImmutable {
/**
* Just a pseudocode - I don't know how to work with ANNOTATIONS :) :) :)
* SORRY :)
* @throws MyImmutableException
*/
private void detectMethod() throws MyImmutableException {
Immutable instance = CLASS_THAT_IS_ANNOTATED.getClass().getAnnotation(Immutable.class)
if (instance != null) {
// get parent Method invocation name (from stacktrace list)
String methodName = .............;
if (methodName.startsWith("set")) {
// check id we have variable with this settername
String fieldName = ...; // cut "set" get rest of it, make first letterSmall
// find this field in object fields
Field f = this.getClass().getDeclaredField(fieldName);
if (f.getAnnotation(ImmutableOnThisInstance.class) != null) {
throw MyImmutableException();
}
}
}
}
}
fonte
2013-01-22 19:35:06
Sì, questa parte "definire costanti" è fuorviante. –
Hmm. Potremmo fare un paio di risposte in più per renderlo veramente chiaro. –
Non dimenticare che Point2D è astratto, quindi non puoi fare Point2D (x, y); – david99world