Java:如何强制类类型参数与泛型方法中指定的泛型类型相同?

时间:2011-06-01 20:13:21

标签: java generics

我创建了一个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);
}

因此,对于某个特定类型的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);

不会导致编译错误,这是我希望它做的。

3 个答案:

答案 0 :(得分:1)

我想出来了。我改变了签名:

public static <E> void broadcastNotify(Class<E> type, E data)

为:

public static <E> void broadcastNotify(Class<E> type, INotification<E> data)

其中INotification是一个包装我试图在通知中返回的数据的接口。这强制类类型必须与通知类型完全匹配,以便映射通知的基础映射将消息正确发送到已注册的侦听器,而不必担心程序员错误。

答案 1 :(得分:0)

避免此问题的一种方法是使用反射并从类本身获取类型。这将避免两次提供相同类型的需要。它只会提供一个警告,使用非泛型类型。

您可以从实现类的接口获取泛型类型。

答案 2 :(得分:0)

位置是一个对象 - 我相信它变成了:

public static <Object> void broadcastNotify(Class<Object> type, Object data) 

请记住,在java中,所有对象都从Object继承。

相关问题