I have an interface which is implemented by 4 different classes. Now, I want to call a setter method of one of the classes through the reference of this interface. The class is decided at run time, and the interface doesn't contain any methods or variables. So how can I set the value of private variables of one of those classes? I provide you the sample of code.
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?
*/
}