samedi 20 février 2016

Replacement for java reflection in method overloading

I have a following class hierarchy:

<code>
public interface Decorator <T> {
    T decorate(String data);
}
public class StringDecorator implements Decorator<String> {
    @Override
    public String decorate(String data) {
        return "Decorated Data";
    }
}
public class IntegerDecorator implements Decorator<Integer> {
    @Override
    public Integer decorate(String data) {
        return 0;
    }
}
public class MyPrint {
    public void printData(String data) {
        System.out.println("String Data: " + data);
    }
    public void printData(Integer data) {
        System.out.println("Integer Data: " + data);
    }
}
</code>

With the above structure in place, I want to first call some decorator function and pass the same result to printData method. Currantly I'm able to achieve this with the help of java reflection as follows:

<code>
void callerFunction(Decorator decorator, MyPrint myPrint){
    // Below line would call appropriate decorator depending on injected type
    Object decoratedData = decorator.decorate("test");
    try {
        // Java reflection to figure out an appropriate overloaded method to be invoked
        myPrint.getClass().getMethod("printData", decoratedData.getClass()).invoke(myPrint, decoratedData);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>

Is there any better way to achieve the same without using reflection? The use case is to call appropriate printData overloaded function depending on the type of data that decorator returns (without using if else on instanceOf).

Thanks.





Aucun commentaire:

Enregistrer un commentaire