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

大憨熊 提交于 2020-01-03 01:21:13

问题


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: e.g. 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: i.e. specify generic values on the fly? thanks in advanced!


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/54057016/how-to-specify-generic-type-when-the-type-is-only-known-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!