如何在运行时调用接口的子类函数?

时间:2014-06-03 03:51:20

标签: java interface private

我有一个由4个不同类实现的接口。现在,我想通过此接口的引用调用其中一个类的setter方法。该类在运行时决定,并且接口不包含任何方法或变量。那么如何设置其中一个类的私有变量的值呢?我为您提供了代码示例。

public interface InterfaceClass {
}

public class ClassOne implements InterfaceClass{
    private String name;

    public void setName(String name) {
        this.name = name;
    }
}

public class ClassTwo implements InterfaceClass {
    private String name;

    public void setName(String name) {
        this.name = name;
    }
}

class CaalingClass {
    String className = "ClassOne";// the value of the string is decide at the run time
    InterfaceClass i = (InterfaceClass) Class.forName(className).newInstance();
    i.setName("ABC"); //this gives an error
    /*
     * I know it should be ((ClassOne) i).setName("ABC"); but at runtime i
     * don know which class is to be called so is there any other way to
     * find or it has to be done in this fashion?
     */
}

1 个答案:

答案 0 :(得分:1)

像这样修改interface InterfaceClass

public interface InterfaceClass {
  public void setName(String name);
}

接下来,将类修改为implement InterfaceClass,如此,

public class ClassOne implements InterfaceClass

public class ClassTwo implements InterfaceClass

现在您发布的程序应该可行。如果没有,请发布完整的例外。实际上,您可能应该将InterfaceClass重命名为有意义的内容,例如Nameable

public interface Nameable {
  public void setName(String name);
  // public String getName(); // <-- From the comments. It's not a bad suggestion.
}