我创建了一个NotificationManager类,让你可以为一些通用的通知服务注册一个通用的监听器.在NotificationManager类中,我有一个通用的方法来注册一个服务的监听器:
public static <E> void registerNotify(Class<E> type, INotificationListener<E> listener) {
@SuppressWarnings("unchecked")
INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
service.registerNotificationListener(listener);
}
Run Code Online (Sandbox Code Playgroud)
因此,对于某个特定类型的INotificationListener,我想强制用户在调用此方法时指定与侦听器相同的类型.该类型映射到相同类型的所有INotificationListener,但是此方法不强制执行我要强制执行的操作.例如,我可以打电话:
INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(String.class, locationListener);
Run Code Online (Sandbox Code Playgroud)
并且代码编译得很好.我认为这将强制实施如下:
INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(Location.class, locationListener);
Run Code Online (Sandbox Code Playgroud)
有关如何实现这一目标的任何想法?
更新:
对不起,混合,上面确实工作.同一类中不起作用的方法实际上如下:
public static <E> void broadcastNotify(Class<E> type, E data)
{
@SuppressWarnings("unchecked")
INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
service.notifyListeners(data);
}
Run Code Online (Sandbox Code Playgroud)
并致电:
Location location = new Location();
NotificationManager.broadcastNotify(Object.class, location);
Run Code Online (Sandbox Code Playgroud)
不会导致编译错误,这是我希望它做的.
我明白了这一点。我更改了签名:
public static <E> void broadcastNotify(Class<E> type, E data)
Run Code Online (Sandbox Code Playgroud)
到:
public static <E> void broadcastNotify(Class<E> type, INotification<E> data)
Run Code Online (Sandbox Code Playgroud)
其中 INotification 是一些接口,它包装了我试图在通知中返回的数据。这强制类类型必须与通知类型完全匹配,以便映射通知的底层映射正确地将消息发送到注册的侦听器,而不必担心程序员错误。