java - 使用接口(interface)时如何为类赋值?

标签 java interface constructor implements

我有一个实现接口(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/

相关文章:

java - 如何在 Calendar Api 中禁用 Google 的 “Video Call” 默认值?

c++ - 指向可配置实现的 Pimpl 成语

c++ - 如何在C++中创建指针数组

unit-testing - 实现 protected 无参数构造函数以进行单元测试

java - spring中如何将事务设置在最底层,类似jdbc?

java - vText 语音密码不会在 Android 上加载

java - 无法在实体中发送服务

c++ - 我的 C++ 游戏架构

java - RMI:如果只有一个 JVM,则远程方法的参数是否必须实现可序列化?

java - 在 Java 运行时向面板添加元素