我在这里会有点笨拙,但是请在投票之前坚持下去并阅读整个回复;)首先,您不能更改最终字段是不正确的。在 Java 中,你几乎可以做任何事情;)检查一下:
public class Movie {
static class FSK { /* TODO */ }
private String title;
private FSK fsk;
private boolean isRent;
private final int serial;
private static int nextSerial;
Movie(String title, FSK fsk) {
this.title = title;
this.fsk = fsk;
this.serial = nextSerial;
nextSerial++;
}
Movie(Movie that) {
this(new String(that.title), that.fsk);
setFinalSerial(that.serial);
}
void setFinalSerial(int newValue) {
try {
java.lang.reflect.Field field = getClass().getDeclaredField("serial");
field.setAccessible(true);
java.lang.reflect.Field modifiersField = java.lang.reflect.Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~java.lang.reflect.Modifier.FINAL);
field.set(this, newValue);
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Movie m1 = new Movie("title", new FSK());
Movie m2 = new Movie(m1);
System.out.println(m1.serial);
System.out.println(m2.serial);
}
}
但这只是一个丑陋的把戏。我猜你的课应该是这样的:
public class Movie {
static class FSK { /* TODO */ }
private String title;
private FSK fsk;
private boolean isRent;
private final int serial;
private static int nextSerial;
Movie(int serial, String title, FSK fsk) {
this.title = title;
this.fsk = fsk;
this.serial = serial;
}
Movie(String title, FSK fsk) {
this (nextSerial++, title, fsk);
}
Movie(Movie that) {
this(that.serial, that.title, that.fsk);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Movie m1 = new Movie("title", new FSK());
Movie m2 = new Movie(m1);
System.out.println(m1.serial);
System.out.println(m2.serial);
}
}
关键是您应该创建“复制构造函数”,您可以在其中设置最终变量而无需任何技巧。