Java: Interface with new keyword how is that possible?

前端 未结 9 1514
抹茶落季
抹茶落季 2020-12-04 08:21

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

This code is from Document.java in jaxb library, and ContentVisitor is an Interfac

9条回答
  •  爱一瞬间的悲伤
    2020-12-04 09:03

    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.

    The code is roughly equivalent to:

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

提交回复
热议问题