我有一个实现接口的Java类,这个类有一个构造函数,它接受一个String值,并且所有的方法都是该类依赖于该值才能得到工作,所以,如果我想要怎么办?直接处理接口并从中访问方法,如你所知,接口不能有构造函数,所以我不能从中分配字符串值。
班级:
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;
}
答案 0 :(得分:1)
您可以将XmlSource
对象分配给XmlInterface
类型引用变量,然后使用该引用变量来调用方法。
XmlInterface obj = new XmlSource(surl);
try
{
boolean configure = obj.configure();
Document document = obj.load();
}
catch(Exception e){
// perform exception handling
}