我对Java和Android都很陌生,我正在开发一个Android RSS阅读器项目。我正在编写以AsyncTask
运行的阅读器,并希望将其尽可能地重复使用。我在阅读器中使用SAX解析器,并希望它接受扩展DefaultHandler
的任何类型的处理程序。但是,当我尝试调用SAXParser
的解析方法时,它并不理解处理程序参数。
cannot resolve method 'parse(org.xml.sax.InputSource,java.lang.Class<capture<? extends org.xml.sax.helpers.DefaultHandler>>)'
在传递通用处理程序方面,这是解决这个问题的正确方法,还是我应该采取不同的做法?
public class RSSFeeder extends AsyncTask<Void, Void, Void>{
private Class<? extends DefaultHandler> handler;
private String feedURL;
public RSSFeeder(Class<? extends DefaultHandler> handler, String feedURL) {
this.handler = handler;
this.feedURL = feedURL;
}
@Override
protected Void doInBackground(Void... params) {
URL feedLocation = null;
try {
feedLocation = new URL(feedURL);
BufferedReader in = new BufferedReader(new InputStreamReader(feedLocation.openStream()));
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
sp.parse(new InputSource(in), handler);
} catch (MalformedURLException murlex) {
Log.d(this.getClass().getName(), "The supplied URL is not valid " + murlex.getMessage());
} catch (IOException iox) {
Log.d(this.getClass().getName(), "Could not read data from the supplied URL: " + feedLocation.toString() + " " + iox.getMessage());
} catch (ParserConfigurationException pcex) {
Log.d(this.getClass().getName(), "Could not configure new parser. " + pcex.getMessage());
} catch (SAXException saxex) {
Log.d(this.getClass().getName(), "Could not create new sax parser. " + saxex.getMessage());
}
return null;
}
答案 0 :(得分:0)
handler
是java.lang.Class
类型的变量,而不是DefaultHandler
(或其任何子类型)。方法SAXParser#parse()
的第二个参数必须是DefaultHandler
类型。您可以尝试将类声明为类型参数扩展为DefaultHandler
的泛型类:
public class RSSFeeder<T extends DefaultHandler> extends AsyncTask<Void, Void, Void>{
private T handler;
public RSSFeeder(T handler, String feedURL) {
this.handler = handler;
this.feedURL = feedURL;
}
...
}