我创建了一个NotificationManager类,让我们向通用通知服务注册一个通用侦听器。在NotificationManager类我有一个与服务注册监听器的一般方法:Java:如何强制类类型参数与通用方法中指定的泛型类型相同?
public static <E> void registerNotify(Class<E> type, INotificationListener<E> listener) {
@SuppressWarnings("unchecked")
INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
service.registerNotificationListener(listener);
}
因此,对于某些特定类型的INotificationListener我想强迫用户,调用此方法时,要指定与听众相同的类型。该类型映射到相同类型的所有INotificationListener,但是此方法不强制执行我试图执行的操作。例如,我可以拨打:
INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(String.class, locationListener);
并且代码编译正常。我认为这将强制执行如下:
INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(Location.class, locationListener);
有关如何完成此任何想法?
更新:
对不起,查询股价,上面是实际可行的。在不工作的同一类的方法实际上是这样的:
public static <E> void broadcastNotify(Class<E> type, E data)
{
@SuppressWarnings("unchecked")
INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
service.notifyListeners(data);
}
,并呼吁:
Location location = new Location();
NotificationManager.broadcastNotify(Object.class, location);
不会导致编译错误,这就是我想它做的事。
什么是'NotificationServiceFactory#get()'的声明返回类型? – 2011-06-01 20:19:41
这是INotificationService >。工厂拥有一个映射,它将类类型名称映射到INotificationServices。我想它应该是INotificationService,但是如何确保用户在通过registerNotify方法中的错误类时遇到编译错误? –
2011-06-01 20:24:05
我不确定,但当我尝试传递'String.class'(Eclipse Helios SR2)时,我只是得到了所需的编译错误。你真的在运行你认为你正在运行的代码吗?或者你使用的是javac还是不同的IDE? – BalusC 2011-06-01 20:37:48