我试过这个:
class protectedfinal
{
static abstract class A
{
protected final Object a;
}
static class B extends A
{
{ a = new Integer(42); }
}
public static void main (String[] args)
{
B b = new B();
}
}
但是我得到了这个错误:
protectedfinal.java:12: error: cannot assign a value to final variable a
{ a = new Integer(42); }
^
1 error
如何解决此问题?
有些人建议在这里使用构造函数,但这仅适用于某些情况。它适用于大多数对象,但无法从构造函数中引用对象本身。
static abstract class X
{
protected final Object x;
X (Object x) { this.x = x; }
}
static class Y extends X
{
Y () { super (new Integer(42)); }
}
static class Z extends X
{
Z () { super (this); }
}
这是错误:
protectedfinal.java:28: error: cannot reference this before supertype constructor has been called
Z () { super (this); }
^
有人可能会争辩说,存储这种引用没有多大意义,因为this
已经存在了。这是正确的,但这是在构造函数中使用this
时发生的一般问题。不可能将this
传递给任何其他对象以将其存储在最终变量中。
static class Z extends X
{
Z () { super (new Any (this)); }
}
那么我怎样才能写一个抽象类,它强制所有子类都有一个在子类中初始化的最终成员呢?
在其构造函数中初始化A.a
。子类将使用super()
将初始值设定项传递给A.a
。
class protectedfinal {
static abstract class A {
protected final Object a;
protected A(Object a) {
this.a = a;
}
}
static class B extends A {
B() {
super(new Integer(42));
}
}
public static void main (String[] args) {
B b = new B();
}
}
在调用超类构造函数之前,不能使用 this
,因为在此阶段对象尚未初始化,即使此时构造函数尚未运行Object
也是如此,因此调用任何实例方法都会导致不可预知的结果。
在您的情况下,您必须以另一种方式解析Z
类的循环引用:
Z () { super (new Any (this)); }
使用非最终字段或更改类层次结构。出于同样的原因,使用实例方法 super(new Any(a()));
的解决方法不起作用:在运行超类构造函数之前,无法调用实例方法。
在我个人看来,你的问题暗示了设计中的缺陷。但是要回答你的问题。如果绝对必要,您可以使用反射更改 java 中的最终字段。
如果一切都失败了,你仍然可以使用sun.misc.unsafe。
但我强烈建议您不要这样做,因为它可能会杀死您的 VM。
我的工作是使用方法而不是最终成员:
class protectedfinal
{
static abstract class AA
{
protected abstract Object a();
}
static class BB extends AA
{
@Override
protected Object a() { return this; }
}
public static void main (String[] args)
{
AA a = new BB();
System.out.println (a.a());
}
}
但我想使用最终成员,因为我认为访问最终成员比调用方法更快。是否有机会与最终成员一起实施它?