仅在运行时知道通用类型时如何指定通用类型? [英] How to specify generic type when the type is only known at runtime?
问题描述
我需要一些代码来动态生成一组子类的泛型类型为1的泛型对象: keyEvent
, mouseEvent
或 appEvent
,这些都扩展了事件
。因此,我的通用类 EventFunction
需要一个模板,但是在接收到该事件之前,我不知道类的类型,因此可以执行以下操作:
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?
推荐答案
以下代码段可能会对您有所帮助:
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;
}
}
}
用法如下:
EventFunctionFactory factory = new EventFunctionFactory();
Event foo = new FooEvent();
EventFunction<Event> function = factory.buildFunction(foo);
这里有一个摘要
< a href = http://tpcg.io/bMNbkd rel = nofollow noreferrer> http://tpcg.io/bMNbkd
这篇关于仅在运行时知道通用类型时如何指定通用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!