【发布时间】: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?
*/
}
【问题讨论】:
-
实现接口的类在哪里。它们只是普通的类