gpt4 book ai didi

返回接口(interface)类型的 Java 方法

转载 作者:行者123 更新时间:2023-11-29 04:36:21 24 4
gpt4 key购买 nike

我看过相关问题,但答案只是绕过了我正在寻找的答案的核心。

我有以下代码行(编译和运行没有错误):

Document doc = dbuilder.parse(myXmlFile);

在哪里文档是接口(interface)org.w3c.dom.Documentparse()是来自 javax.xml.parsers.DocumentBuilder 的方法

当我执行

System.out.println(doc.getClass().getName());

它的输出是

com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl

我认为这意味着 DeferredDocumentImpl实现 Document接口(interface),并且当我对我的 doc 变量执行方法时,我实际上是在执行 DeferredDocumentImpl 的方法。

我的问题是:

  1. 上面的假设是否正确,也就是说,我确实在执行那个 DeferredDocumentImpl 的实现方法吗?上课?

  2. 一个接口(interface)可以被任意数量的类实现,假设org.w3c.dom.Document确实是由多个类实现的,为什么Document parse() 返回的类型被选为DeferredDocumentImpl类,而不是实现 Document 的其他类之一?

  3. 假设上面的 2. 是某种“默认”或“优先”类型分配,我在哪里验证 - 并可能更改 - 该分配?

  4. 我如何在代码本身的级别覆盖上面 3. 中描述的类型分配?

正如我所说,我尽职尽责地搜索了这个,但似乎没有任何东西能给我这些具体问题的答案......非常感谢。

最佳答案

am I indeed executing the implemented methods of that DeferredDocumentImpl class?

是的

An interface can be implemented by any number of classes, and assuming that org.w3c.dom.Document is indeed implemented by multiple classes, why did the Document type returned by parse() get cast as the DeferredDocumentImpl class, and not one of the other classes that implements Document?

您需要阅读代码以确定该库返回该实现的原因。如果它是该库唯一的实现,我不会感到惊讶。

注意:org.w3c.dom.Document是一个API标准接口(interface),实现该API的库只需要提供一个实现即可。库不必从另一个库创建实现。

Assuming that 2. above is some kind of 'default' or 'priority' type-assignment, where do I verify - and possibly change - that assignment?

是的,通过修改库的源来更改库创建的对象。

How would I override the type-assignment I describe in 3. above at the level of the code itself?

检查源代码的副本,更改并构建它。

关于返回接口(interface)类型的 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41308199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com