how to call subclass function of interface at runtime?
本问题已经有最佳答案,请猛点这里访问。
我有一个由4个不同的类实现的接口。现在,我想通过这个接口的引用调用其中一个类的setter方法。类在运行时确定,接口不包含任何方法或变量。那么,如何设置这些类中某个类的私有变量的值呢?我向您提供代码示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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 2 3 |
接下来,像这样将类修改为
1 2 3 | public class ClassOne implements InterfaceClass public class ClassTwo implements InterfaceClass |
现在你发布的程序可以工作了。如果没有,请发布完整的异常。实际上,你应该把你的
1 2 3 4 | public interface Nameable { public void setName(String name); // public String getName(); // <-- From the comments. It's not a bad suggestion. } |