简体   繁体   中英

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!

but I do know that the type of data is the same as executor's parameterised type, T

If you are sure, you can write:

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

Executor<Data> executorData = (Executor<Data>)executor;

executorData.execute(data);

It works for

List<? extends Number> list = new ArrayList<>();
List<Number> listNumbers = (List<Number>) list; //Unchecked cast: 'java.util.List<capture<? extends java.lang.Number>>' to 'java.util.List<java.lang.Number>
listNumbers.add(new Integer(1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM