简体   繁体   中英

How to specify generic type when the type is only known at runtime?

I have some code that I need to generate a generic object on the fly with the generic type of 1 of a set of subclasses: eg keyEvent , mouseEvent or appEvent , these all extend event . So, my generic class EventFunction requires a template, however I dont know what the class type is until I recieve the event, so is there a way to do the following:

Event event = new KeyEvent(); // FOR EXAMPLE RECIEVING A KEY EVENT
// Require an EventFunction with that event class as the generic type
EventFunction<event.getClass()> func = new EventFunction<event.getClass()>(event);

How do I do the above: ie specify generic values on the fly?

The following snippet may help you:

class Event { }

class FooEvent extends Event { }

class EventFunction<T extends Event> {
    public EventFunction(T event) { }
}

class EventFunctionFactory {
   public <T extends Event> EventFunction<T> buildFunction(T event) {
       if (event.getClass().equals(FooEvent.class)) {
            System.out.println("A new FooEventFunction!");          
            return new EventFunction<T>(event);
       }
       else {
           return null;
       }
   }
}

Usage is as follows:

    EventFunctionFactory factory = new EventFunctionFactory();
    Event foo = new FooEvent();
    EventFunction<Event> function = factory.buildFunction(foo);

Here you have a snippet

http://tpcg.io/bMNbkd

Generics only exist for the compiler to check the type safety at compile-time. If your type argument is only known at runtime and not at compile-time, there would be no point to use generics there.

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