我有一个带有private static final字段的类,不幸的是,我需要在运行时更改.
使用反射我得到这个错误: java.lang.IllegalAccessException: Can not set static final boolean field
有没有办法改变价值?
Field hack = WarpTransform2D.class.getDeclaredField("USE_HACK");
hack.setAccessible(true);
hack.set(null, true);
Run Code Online (Sandbox Code Playgroud) 我正在阅读有关transient和final关键字的内容,我找到了一个答案,我们不能使用带有final关键字的transient关键字.我试过并感到困惑,因为这里工作正常.
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class SerExample{
public static void main(String... args){
Student foo = new Student(3,2,"ABC");
Student koo = new Student(6,4,"DEF");
try
{
FileOutputStream fos = new FileOutputStream("abc.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(foo);
oos.writeObject(koo);
oos.close();
fos.close();
}
catch(Exception e){/**/}
try{
FileInputStream fis = new FileInputStream("abc.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println(ois.readObject());
System.out.println(ois.readObject());
fis.close();
ois.close();
}catch(Exception e){/**/}
}
}
Run Code Online (Sandbox Code Playgroud)
这是Serializable Student类代码:
class Student implements Serializable{
private transient final int id;
private transient …Run Code Online (Sandbox Code Playgroud)