我正在从Java库中读取一些源代码,我在这里很困惑;
此代码来自jaxb库中的Document.java,而ContentVisitor是同一个包中的Interface,我们如何使用new关键字创建Interface实例?这不是非法的吗?
public final class Document {
.
.
private final ContentVisitor visitor = new ContentVisitor() {
public void onStartDocument() {
throw new IllegalStateException();
}
public void onEndDocument() {
out.endDocument();
}
public void onEndTag() {
out.endTag();
inscopeNamespace.popContext();
activeNamespaces = null;
}
}
Run Code Online (Sandbox Code Playgroud)
NPE*_*NPE 57
在代码中,您不是要创建接口的实例.相反,代码定义了一个实现接口的匿名类,并实例化该类.
代码大致相当于:
public final class Document {
private final class AnonymousContentVisitor implements ContentVisitor {
public void onStartDocument() {
throw new IllegalStateException();
}
public void onEndDocument() {
out.endDocument();
}
public void onEndTag() {
out.endTag();
inscopeNamespace.popContext();
activeNamespaces = null;
}
}
private final ContentVisitor visitor = new AnonymousContentVisitor();
}
Run Code Online (Sandbox Code Playgroud)
Nis*_*ant 13
这是有效的.它被称为匿名类.看这里
我们已经看到了定义和实例化匿名类的语法示例.我们可以更正式地表达这种语法:
Run Code Online (Sandbox Code Playgroud)new class-name ( [ argument-list ] ) { class-body }要么:
Run Code Online (Sandbox Code Playgroud)new interface-name () { class-body }
| 归档时间: |
|
| 查看次数: |
20418 次 |
| 最近记录: |