重新设计未经检查的投放警告 [英] Redesigning around unchecked cast warnings

查看:51
本文介绍了重新设计未经检查的投放警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,其中将包含一些针对不同对象的不同解析器实现.虽然我可以存储解析器实现而没有任何警告,但是从映射中获取解析器会警告未检查的强制转换异常.下面是一个简化的摘录:

I have a class will contain a few different parser implementations for different objects. While I am able to store the parser implementations without any warnings, getting a parser from the map warns about an unchecked cast exception. Below is a simplified excerpt:

private Map<Class<?>, Parser<?>> parsers = new HashMap<>();

public <T> void addParser(Class<T> type, Parser<T> parser) {
    parsers.put(type, parser);
}

private <T> Parser<T> parserFor(Class<T> type) {
    // Compiler complains about unchecked cast below
    return (Parser<T>) parsers.get(type);
}

是否存在另一种实现类似逻辑而不引起未经检查的强制转换警告的方法?

Is there another way to implement similar logic without causing an unchecked cast warning?

推荐答案

无法创建Map<Class<...>, Parser<...>>,其中... -s可以是任何东西,但必须在键及其值之间进行匹配.因此,您无法让编译器为您做检查,因此保证检索Class<T>可以保证为您提供Parser<T>.但是,您的代码本身是正确的. 知道您的演员表是正确的,即使编译器不正确.

There's no way to create a Map<Class<...>, Parser<...>> where the ...-s can both be anything but have to match between a key and its value; so there's no way that you can get the compiler to do the checking for you, where retrieving a Class<T> is guaranteed to give you a Parser<T>. However, your code itself is correct; you know that your cast is correct, even though the compiler does not.

因此,当您知道自己的转换正确无误,但 Java 不知道该怎么做时,您该怎么办?

So, when you know that your cast is correct, but Java doesn't know it, what can you do?

最好,最安全的方法是编写尽可能小的代码,负责处理已检查和未检查的逻辑之间的转换,并确保未检查的逻辑不会引起任何错误. .然后,您只需使用适当的@SuppressWarnings批注标记该代码.例如,您可以输入以下内容:

The best and safest approach is to craft a specific piece of your code, as small as possible, that is responsible for handling the translation between checked and unchecked logic, and for making sure that the unchecked logic doesn't cause any mistakes. Then, you just mark that code with the appropriate @SuppressWarnings annotation. For example, you can have something like this:

public abstract class Parser<T> {
    private final Class<T> mType;

    protected Parser(final Class<T> type) {
        this.mType = type;
    }

    public final Class<T> getType() {
        return mType;
    }

    @SuppressWarnings("unchecked")
    public final <U> Parser<U> castToParserOf(final Class<U> type) {
        if (type == mType) {
            return (Parser<U>) this;
        } else {
            throw new ClassCastException("... useful message ...");
        }
    }
}

在您的示例中,这将使您可以安全地编写:

This would allow you to safely write, in your example:

public <T> void addParser(final Parser<T> parser) {
    parsers.put(parser.getType(), parser);
}

private <T> Parser<T> parserFor(final Class<T> type) {
    return parsers.get(type).castToParserOf(type);
}

这篇关于重新设计未经检查的投放警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆