声明中的泛型类型如果从未使用过它会如何真正影响该方法?

时间:2018-01-21 00:55:18

标签: java generics htmlunit

我正在浏览HTMLUnit源代码,并且无法弄清楚泛型类型应该如何在这里工作。它从未在方法中使用过,使方法具有通用性的重点是什么?

public <T> List<T> getByXPath(final String xpathExpr) {
        PrefixResolver prefixResolver = null;
        if (hasFeature(XPATH_SELECTION_NAMESPACES)) {
            /*
             * See if the document has the SelectionNamespaces property defined.  If so, then
             * create a PrefixResolver that resolves the defined namespaces.
             */
            final Document doc = getOwnerDocument();
            if (doc instanceof XmlPage) {
                final ScriptableObject scriptable = ((XmlPage) doc).getScriptableObject();
                if (ScriptableObject.hasProperty(scriptable, "getProperty")) {
                    final Object selectionNS =
                            ScriptableObject.callMethod(scriptable, "getProperty", new Object[]{"SelectionNamespaces"});
                    if (selectionNS != null && !selectionNS.toString().isEmpty()) {
                        final Map<String, String> namespaces = parseSelectionNamespaces(selectionNS.toString());
                        if (namespaces != null) {
                            prefixResolver = new PrefixResolver() {
                                @Override
                                public String getBaseIdentifier() {
                                    return namespaces.get("");
                                }

                                @Override
                                public String getNamespaceForPrefix(final String prefix) {
                                    return namespaces.get(prefix);
                                }

                                @Override
                                public String getNamespaceForPrefix(final String prefix, final Node node) {
                                    throw new UnsupportedOperationException();
                                }

                                @Override
                                public boolean handlesNullPrefixes() {
                                    return false;
                                }
                            };
                        }
                    }
                }
            }
        }
        return XPathUtils.getByXPath(this, xpathExpr, prefixResolver);
    }

2 个答案:

答案 0 :(得分:2)

此处的通知用于将T类型infer用于XPathUtils.getByXPath方法,签名为

public static <T> List<T> getByXPath(DomNode node, String xpathExpr, PrefixResolver resolver)

当编译器查看此语句时

return XPathUtils.getByXPath(this, xpathExpr, prefixResolver);

它从外部T方法推断getByXPath类型,后者又从其调用中推断出T

因此,如果您致电List<HtmlDivision> list = page.getByXPath(expr);,那么HtmlDivision将被推断为getByXPath,然后进入XPathUtils.getByXPath

答案 1 :(得分:1)

它用于返回类型(List<T>),因此返回的List将具有该特定的泛型类型。这也意味着XPathUtils.getByXPath(…)会返回List<T>,因为它会在方法的底部返回它,因此它会在方法中使用。< / p>