【问题标题】:how to call subclass function of interface at runtime? [duplicate]如何在运行时调用接口的子类函数? [复制]
【发布时间】:2014-07-23 07:06:50
【问题描述】:

我有一个由 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?
     */
}

【问题讨论】:

  • 实现接口的类在哪里。它们只是普通的类

标签: java interface private


【解决方案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.
}

【讨论】:

  • 不行,因为ClassOneClassTwo没有实现接口InterfaceClass
  • @Braj 谢谢。已编辑。
  • 为什么在这种情况下使用反射?只需使用多态性。在接口中再创建一个方法getName()来取回值,否则setName()根本没有意义。
  • @Braj 这似乎是一个过分的假设;也许他们以不同的方式实现toString()。现在,命名一个接口 InterfaceClass - 这在很多层面上都是错误的。
  • 哦,对不起!我只是错过了.. 但是除了在接口中声明 setter 方法并使用我知道的名称进行类型转换之外别无他法。可以在运行时定义的东西
猜你喜欢
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2020-08-23
  • 2021-11-15
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多