Thursday, January 22, 2015

How do I supply an argument to a parameterized method, whose type I don't know until runtime?

In this code snippet:



...
Executor<? extends Data> executor = someOtherThing.getExecutor();
Data data = someOtherOtherThing.getData();

executor.execute(data);
...

interface Executor<T extends Data> {
void execute(T data);
}


So both the executor and the data are coming in from somewhere else, and I don't know their actual types until run time, but I do know that the type of data is the same as executor's parameterised type, T.


I assume that some sort of cast is needed to allow executor.execute(data), but I don't know what to cast to, or how to do it, without knowing the exact type until runtime. How can I make this happen?


Thank you!


No comments:

Post a Comment