Somebody help me with these generics!
If you have an overloaded method with different types which can be an argument, can one write a generic method which at runtime call the right one? (Sorry if my java-nology is poor, if so)
Example:
public interface CoolInterface {
setOverloadedValue(String o);
setOverloadedValue(Integer o);
setOverloadedValue(Date o);
}
public interface ClazzProvider {
Class getClazz();
}
public class SomeUncoolClass {
@AutowiredMagic CoolInterface coolGuy;
@AutowiredMagic ClazzProvider clazzyProvider;
public void helpMeMethod() {
coolGuy.setOverloadedValue(getValue(clazzyProvider.getClazz()));
}
private ??? getValue(???) {
return ???;
}
}
What is the method signature of getValue()? And how can i implement it?
No – the overload is selected at compile time, and the compiler can’t tell which overload you want to use.
You might want to have a look at at the Visitor Pattern as a workaround for the case where the types you want to accept are under your control – it doesn’t help much when you want to accept String/Date/Object though 🙁