繁体   English   中英

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

[英]Java: How do you enforce a class type parameter to be the same as generic type specified in a generic method?

我创建了一个 NotificationManager class,它让您可以为一些通用通知服务注册一个通用侦听器。 在 NotificationManager class 我有一个通用的方法来注册一个服务的监听器:

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

关于如何做到这一点的任何想法?


更新:

抱歉混淆了,上面确实有效。 同一个 class 中不起作用的方法实际上如下:

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

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

我想通了。 我更改了以下签名:

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

至:

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

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

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

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

位置是 Object - 我相信它会变成:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM