Java:与 new 关键字的接口怎么可能? [英] Java: Interface with new keyword how is that possible?

查看:17
本文介绍了Java:与 new 关键字的接口怎么可能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 Java 库中读取一些源代码,在这里我很困惑;

I was reading some sourcecode from Java libraries, and I am confused here;

这段代码来自 jaxb 库中的 Document.java,ContentVisitor 是一个 Interface 在同一个包中,我们如何创建一个带有 new 关键字的 Interface 实例?这不违法吗?

This code is from Document.java in jaxb library, and ContentVisitor is an Interface in same package, how can we create an instance of Interface with a new keyword? isn't that illegal?

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;
    }
}

推荐答案

在代码中,您没有创建接口的实例.相反,代码定义了一个匿名类来实现接口,并实例化该类.

In the code, you're not creating an instance of the interface. Rather, the code defines an anonymous class that implements the interface, and instantiates that class.

代码大致相当于:

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();
}

这篇关于Java:与 new 关键字的接口怎么可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆