我有一個Java類實現了一個接口,這個類有一個構造函數,它接受一個字符串值,所有的方法都是那個類爲了得到工作而依賴那個值,所以,我可以做什麼,如果我想要直接處理接口並從中訪問它的方法,因爲你知道接口不能有構造函數,所以我不能從它分配字符串值。如何在使用接口時爲類指定值?
的Class:
public class XmlSource implements XmlInterface{
XmlConf xconf = new XmlConf();
URLProcess urlp = new URLProcess();
private URL url;
private String surl;
public XmlSource(String surl) throws MalformedURLException {
this.surl = surl;
result = urlp.validate(surl);
if(result == true){
configure();
}
}
public boolean configure() throws MalformedURLException {
url = new URL(surl);
xconf.setUrl(url);
xconf.setParameters(urlp.parameters);
xconf.setUrlPath(urlp.path);
xconf.setHostName(urlp.hostName);
return result;
}
public Document load() throws IOException, ParserConfigurationException,
SAXException {
// encoding the URL
InputStream is = url.openStream();
// loading the XML
domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
builder = domFactory.newDocumentBuilder();
doc = builder.parse(is);
return doc;
}
}
的接口:
public interface XmlInterface {
public boolean configure() throws Exception;
public Document load() throws Exception;
}
爲了應對該接口中的方法,創建一個實現接口的類的實例,並呼籲類的方法,你的情況爲@TheNewIdiot說使用'新XmlSource(URL)' –
不需要公開您的界面中的方法。默認情況下它們總是公開的。 ''布爾configure()拋出異常;'是足夠的... –