【问题标题】:How to avoid the use of raw type and use generics instead when the type is unknown?当类型未知时,如何避免使用原始类型并使用泛型?
【发布时间】:2015-06-30 05:51:43
【问题描述】:

我有一个处理程序的通用接口:

public interface EventHandler<T> {

     boolean handleEvent(T message);
}

你可以实现这个接口并处理T message。您必须将您的实现实例传递给EventDispatcher 实例。该类在内部存储多个EventHandler 各种类型的实例。

在某个时刻触发了一个事件,EventDispatcher 实例调用相应的EventHandler 的handleEvent() 方法并传递与EventHandler 相同类型的消息。问题是我不知道哪个是确切的类型,但我确信我传递给EventHandler 实例的T message 具有相同的“T”。

我进行此调用的方式使用原始类型和工作方式:

EventHandler handler = getHandler();
Object message = getMessage();
handler.handleEvent(message);

,但我收到警告“未经检查地调用 'handleEvent(T)' 作为原始类型 'EventHandler' 的成员”。

是否可以使用泛型来避免警告?

我想到的一个可能的解决方案是制作一个通用的包装方法:

private <T> boolean handleEventGeneric(EventHandler<T> handler, T message) {
    return handler.handleEvent(message);
}

并使用它:

EventHandler handler = getHandler();
Object message = getMessage();
handleEventGeneric(action.eventHandler, message);

但我不喜欢我必须制作一个包装器方法的事实。有没有更优雅的解决方案?

【问题讨论】:

  • 第二个代码 sn-p 仍在使用原始类型。
  • 但这听起来像是一个无法解决的问题;您正在尝试基于仅在运行时可用的信息来使用编译时类型安全。
  • 最后一个代码示例没有使用handler 变量。有错误吗?另请提供getHandler() 和getMessage() 方法的签名。
  • 我认为你的问题是getMessage()。为什么返回Object?
  • @Oliver Charlesworth 你是对的。它仍然使用原始类型,但我没有收到编译器警告。实际上,您所说的尝试使用基于运行时信息的编译时安全性似乎就是这种情况。我只是想确保没有其他选择。

标签: java events generics raw-types


【解决方案1】:

无法删除此警告(或至少没有@SuppressWarning)。摆脱它的唯一方法是做两件事:

  1. 使您的代码类型证明:因此,基本上,如果调用代码不使用原始类型,那么您就是类型安全的,或者调用代码使用的是原始类型,如果代码最终不是类型安全的,那就是错误
  2. 在您的代码中添加@SuppressWarning("unchecked")。

警告的存在是为了让您可以轻松地确定代码中类型安全方面的弱点。如果您正确使用注释,那么您的代码是安全的,并且您肯定不会得到任何令人不快的ClassCastException,除非您愿意在您实际上并不完全确定该类型是否安全的地方添加@SuppressWarning("unchecked") .

查看一些演示代码来说明我的观点:

import java.util.HashMap;
import java.util.Map;

public class TestGenerics {

    private Map<Class<?>, EventHandler<?>> handlers = new HashMap<Class<?>, TestGenerics.EventHandler<?>>();

    public interface EventHandler<T> {

        boolean handleEvent(T message);
    }

    // Here you force the invoker to provide the correct type of event handler
    // with the given type of klass
    // If he wants to make this fail, then he will have to use rawtype
    public <T> void registerHandler(Class<T> klass, EventHandler<T> handler) {
        handlers.put(klass, handler);
    }

    public <T> void handle(T message) {
        @SuppressWarnings("unchecked") // Here you can add this annotation since you are forcing any invoker to provide a correct EventHandler
        EventHandler<T> handler = (EventHandler<T>) handlers.get(message.getClass());
        if (handler != null) {
            handler.handleEvent(message);
        }
    }

    public static void main(String[] args) {
        TestGenerics test = new TestGenerics();
        test.registerHandler(Long.class, new EventHandler<Long>() {
            @Override
            public boolean handleEvent(Long message) {
                System.out.println("Received a long " + message);
                return true;
            }
        });
        // Here I use raw type but this also means that I created a weak spot in
        // terms of type safety
        EventHandler handler2 = new EventHandler<String>() {
            @Override
            public boolean handleEvent(String message) {
                System.out.println("THis will never print " + message);
                return false;
            }
        };
        test.registerHandler(Integer.class, handler2); // This is where the
                                                        // problem comes from
        test.handle(3L); // OK
        test.handle(1); // ClassCastException

    }

}

【讨论】:

    【解决方案2】:

    你可以这样做:

    EventHandler<Object> handler = getHandler();
    Object message = getMessage();
    handler.handleEvent(message);
    

    虽然不安全,但不亚于现在的安全。

    【讨论】:

    • 其实这是非常错误的。这正是你不应该做的。用你更习惯的东西替换这个 sn-p List&lt;Object&gt; list = getList(); list.add("MyString"); 你有 public List getList() { return some List&lt;Integer&gt; }; 你最终会出现堆污染,因为你正在将一个字符串添加到一个整数列表中。
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多