簡體   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