0

我有一个实现接口的 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;
}
4

1 回答 1

1

您可以将XmlSource对象分配给XmlInterface类型引用变量,然后使用该引用变量来调用方法。

XmlInterface obj = new XmlSource(surl);
try
{
    boolean configure = obj.configure();
    Document document = obj.load();
}
catch(Exception e){
 // perform exception handling
}
于 2013-05-29T11:00:21.407 回答