-3

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?
     */
}
danlei
  • 14,121
  • 5
  • 58
  • 82

1 Answers1

1

Modify your interface InterfaceClass like so,

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

Next, modify your classes to implement InterfaceClass like so,

public class ClassOne implements InterfaceClass

public class ClassTwo implements InterfaceClass

Now your posted program should work. If not, post the full Exception. Actually, you should probably rename your InterfaceClass to something meaningful like Nameable,

public interface Nameable {
  public void setName(String name);
  // public String getName(); // <-- From the comments. It's not a bad suggestion.
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • No it will not work because `ClassOne` and `ClassTwo` are not implementing the interface `InterfaceClass`. – Braj Jun 03 '14 at 04:00
  • why use reflection in this case? simply use **polymorphism**. Make one more method `getName()` in interface to get the value back otherwise there is no meaning of `setName()` at all. – Braj Jun 03 '14 at 04:01
  • @Braj That seems an assumption too far; perhaps they implement `toString()` differently. Now, naming an interface InterfaceClass - that's just wrong on many levels. – Elliott Frisch Jun 03 '14 at 04:04
  • oh m sorry!! i just missed that.. but tis there no other way than either declaring setter method in interface and type casting with the name i know. something tha could be defined at runtime – user3701528 Jun 03 '14 at 04:05