我有一个实现接口(interface)的Java类,这个类有一个接受字符串值的构造函数,并且该类的所有方法都依赖于该值才能工作,所以,如果我想要的话我能做什么直接处理接口(interface)并从中访问方法,正如您所知,接口(interface)不能有构造函数,因此我无法从中分配该字符串值。
类(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;
}
最佳答案
您可以将 XmlSource
对象分配给 XmlInterface
类型引用变量,然后使用该引用变量调用方法。
XmlInterface obj = new XmlSource(surl);
try
{
boolean configure = obj.configure();
Document document = obj.load();
}
catch(Exception e){
// perform exception handling
}
关于java - 使用接口(interface)时如何为类赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16812031/