【问题标题】:How to specify generic type when the type is only known at runtime?当类型仅在运行时已知时如何指定泛型类型?
【发布时间】:2019-06-01 02:13:09
【问题描述】:

我有一些代码需要使用一组子类的泛型类型 1 动态生成泛型对象:例如keyEventmouseEventappEvent,这些都扩展了 event。所以,我的通用类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);

如何执行上述操作:即动态指定通用值?

【问题讨论】:

  • 但是你甚至不知道类型,编译时的语言应该怎么知道?泛型是一种编译时机制(嗯,主要是)。
  • @Shadov:我认为这是伪代码,它会写下intent
  • 你想用func做什么?直到运行时才能知道具体的参数化类型,因此指定一个是没有意义的。通用超类型是Event。如果func 成为EventFunction&lt;Event&gt;,你会怎么做?我认为,如果您想在使用 func 时获得具体类型,则必须强制转换 无论如何

标签: java class object templates generics


【解决方案1】:

下面的 sn-p 可能会对你有所帮助:

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;
       }
   }
}

用法如下:

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

这里有一个sn-p

http://tpcg.io/bMNbkd

【讨论】:

    【解决方案2】:

    泛型仅用于编译器在编译时检查类型安全。如果您的类型参数仅在运行时而不是在编译时已知,那么在此处使用泛型是没有意义的。

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多