Cannot cast from XPathExpression<Object> to XPathExpression<Content>

58 views Asked by At

I'm trying to write a method to execute a JDOM2 XPath. I would like to be able to pass in any type of filter (e.g. Filter<Content> or Filter<Element>. I'm passing in an Element. Element is an interface that extends the Content filter. The compiler warns

"The method executeXPath(Document, String, String, Filter<Content>) in the type XMLUtilities is not applicable for the arguments (Document, String, String, Filter<Element>)"

Is there a way to do this without having to create a separate method for each of the Content types?

Filter<Element> filter = new org.jdom2.filter.ElementFilter();
List<Element> xPathSearchedNodes = XMLUtilities.executeXPath(doc, "/x:root","http://www.example.com",filter);

....

static public List<Content> executeXPath(Document document, String xpathStr, String namespace, Filter<Content> filter) {...}
1

There are 1 answers

1
Ian Roberts On BEST ANSWER

You could make your method generic:

static public <T extends Content> List<T> executeXPath(Document document, String xpathStr, String namespace, Filter<T> filter) {...}

If you pass it a Filter<Content> it returns a List<Content>, if you pass it a Filter<Element> it'll return a List<Element>, etc.