简体   繁体   English

当类型仅在运行时已知时如何指定泛型类型?

[英]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 .我有一些代码需要使用一组子类的通用类型 1 动态生成通用对象:例如keyEventmouseEventappEvent ,这些都扩展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:所以,我的通用类EventFunction需要一个模板,但是在收到事件之前我不知道类类型是什么,所以有没有办法做到以下几点:

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 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.如果您的类型参数仅在运行时已知而不是在编译时已知,那么在那里使用泛型就没有意义了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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