【发布时间】:2022-01-14 11:50:01
【问题描述】:
考虑以下来自 JLS 的文章:§15.9.5.1 当匿名类扩展一个内部类时——那么对于匿名类的隐式构造函数——以下是关于隐式构造函数体的规则:
构造函数体由显式构造函数调用(第 8.8.7.1 节)组成
o.super(...)的形式,其中o是构造函数的第一个形参, 而实际参数是构造函数的后续形参, 按照声明的顺序。
以下是我们从中了解到的——:
-
o- 是类的实例 - 只是封装了匿名类的超类。 - 当我们执行
o.super(...)时,实际上是在调用封闭实例的超类。
考虑以下程序:
class A_ {
public A_(Boolean st){}
public class B_ {
public B_(Integer a){}
public class C_ {
public C_(String str){}
}
}
}
//when creating the anonymous constructor out of C - in a separate class:
public class ThisInAnonymousTesting {
public static void main(String[] args) {
A_.B_.C_ member =
new A_(true)
.new B_(23)
.new C_("Hey"){
};
}
}
现在当我们反编译匿名类时,我们得到以下信息:
/**
=== Anonymous class Declaration
*/
import A_.B_;
import A_.B_.C_;
final class ThisInAnonymousTesting$1 extends C_ {
// - Rule : the 1st argument is the class instance which is the enclosing instance
// of the Super class(C in this case) - ie B
ThisInAnonymousTesting$1(B_ x0, String str) {
x0.getClass();
//But the super() invocation here is for the super class - not for the enclosing instance
super(x0, str);
}
}
以下是我的问题:
- 为什么我们需要做
o.super(...)- 当我们已经将o的初始化实例传递给匿名类构造函数时?- 即
o仅在其超类已被调用时才会创建。 - 构造函数中的
super()调用显然试图实例化C_类,这很好——因为它是当前匿名类的超类。
- 即
- 在反编译的版本中,
x0.getClass();需要什么-我的意思是为什么JVM需要做getClass()?
不确定我对o.super() 子句的解释是否正确?
【问题讨论】:
-
我无法复制。我没有在字节码中收到任何对
getClass的调用。你用的是什么版本的Java,你用的是什么反编译器? -
@Sweeper :我的问题主要是关于提到的
o.super()子句-此语法旨在调用封闭实例的super类-我怀疑为什么需要这样做? - 当封闭实例已经被实例化并通过时? -- 这部分规范是否适用,或者我的理解不正确? --super()也可以作为当前类构造函数调用-但不清楚为什么封闭类会发生这种情况?
标签: java constructor inner-classes jls anonymous-inner-class