mercredi 2 septembre 2015

Dynamically call correct correct setter method with Reflection

I'm working with a library that I cannot modify, which has a class with the following Enum and setters.

public class MyClass {
  public enum MyEnum {
    ClassA,
    ClassB,
    ClassC
    ...
  }

  private SomeEnum myEnum;
  private Interface ifc; // parent of ClassA, ClassB, ClassC, etc.

  public ClassA setClassA(ClassA classA) {
    ifc = classA;
    myEnum= SomeEnum.ClassA;
  }
  public ClassB setClassB(ClassB classB) {
    ifc = classB;
    myEnum= SomeEnum.ClassB;
  }
  public ClassC setClassC(ClassC classC) {
    ifc = classC;
    myEnum= SomeEnum.ClassC;
  }
  // ... more of these setters 
}

Notice how each Enum name is a string literal match of a corresponding class name which implements Interface, and how each class name has its own specific setter.

The code calling this is otherwise straightforward, as you would imagine:

Interface ifc = someCallToGetAnImpl();
MyClass myClass = new MyClass(); 
myClass.set???(ifc);

There are a lot of implementations of Interface, and I cannot guarantee that a future release of the library will not add more. So I am looking to create a function that can dynamically derive and call the correct setter.

I could, of course, build a big old if... else if... block, but that would require a software change when new implementations of Interface are built. I'd also considered looking into using Class.getDeclaredMethod(String name, Class<?>... parameterTypes) by building the name argument using something like

"set + ifc.getClass.getSimpleName()"...

That should keep the software dynamic, but seems kludgy.

Any clean, production-quality suggestions or approaches would be welcome.





Aucun commentaire:

Enregistrer un commentaire