这是一个奇怪的问题,不可变但可变,私有但公开......正确的方法应该是让它们受到保护,正如大家所说的那样。
无论如何,如果安全管理器没有抱怨,你可以在 java 中使用肮脏的技巧,检查一下:
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Priv
{
public static class A
{
private final int x;
public A(int x)
{
this.x = x;
}
}
public static class B extends A
{
public B(int x)
{
super(x);
}
public void setX(int x)
{
Class c = A.class;
try
{
Field f = c.getDeclaredField("x");
f.setAccessible(true);
f.set(this, x);
} catch (IllegalArgumentException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchFieldException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int getX()
{
int v = 0;
try {
Class c = A.class;
Field f = c.getDeclaredField("x");
f.setAccessible(true);
v = f.getInt(this);
} catch (IllegalArgumentException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchFieldException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
}
return v;
}
}
public static void main(String[] args)
{
B b = new B(5);
System.out.println("b.x is " + b.getX());
b.setX(42);
System.out.println("b.x now is " + b.getX());
}
}