我对Java和Android还是很陌生,并且正在从事Android RSS阅读器项目。我正在编写运行为的阅读器AsyncTask
,并希望使其尽可能保持可重用性。我在阅读器中使用了SAX解析器,并且希望它接受任何extension类型的处理程序DefaultHandler
。但是,当我尝试调用的parse方法时SAXParser
,它不理解handler参数。
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;
}
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;
}
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句