简体   繁体   English

Java 通用:未经检查的演员表

[英]Java generic: Unchecked cast

I must use Java 17 (LTS).我必须使用 Java 17 (LTS)。

The following code works fine, but I have the following warning:以下代码工作正常,但我有以下警告:

Unchecked cast...

I am not able to get rid of this warning, whatever I do with my classes.无论我在课堂上做什么,我都无法摆脱这个警告。

The class where the warning appears:出现警告的 class :

public abstract class Parser<T> {

    protected static <T> Parser<T> build(Class<T> parserType, InputArgGroup arguments) {
        Parser<T> parser;
        if (parserType.isAssignableFrom(Name.class)) {
            parser = (Parser<T>) new NameParser();    <- UNCHECKED CAST: x.NameParser to x.Parser<T>
        } else {
            parser = (Parser<T>) new AddressParser(); <- UNCHECKED CAST: x.AddressParser to x.Parser<T>
        }

        parser.hasTitle(arguments.hasTitle());
        parser.hasHeader(arguments.hasHeader());
        parser.setDateTimePattern(arguments.getDateTimePattern());
        ...
        return parser;
    }

    ... common methods ...

    public abstract List<T> parse(String file);
}

Parser 1:解析器 1:

public class NameParser extends Parser<Name> {
    @Override
    public List<Name> parse(String file) {
        System.out.println("parse name CSV");
        return null;
    }
}

Parser 2:解析器 2:

public class AddressParser extends Parser<Address> {
    @Override
    public List<Address> parse(String file) {
        System.out.println("parse address CSV");
        return null;
    }
}

Test:测试:

public class Aaa {
    public Aaa() {
        var addressParser = Parser.build(Address.class, ...);
        var nameParser = Parser.build(Name.class, ...);

        List<Address> addresses = addressParser.parse("addresses.csv");
        List<Name> names = nameParser.parse("names.csv");

    }

    public static void main(String[] args) {
        new Aaa();
    }
}

Any help is appreciated.任何帮助表示赞赏。

It's only a warning to let you know the compiler can't guarantee the cast won't fail at runtime.这只是一个警告,让您知道编译器不能保证强制转换在运行时不会失败。 You know it will work, but the compiler isn't sophisticated enough to figure it out too.你知道它会起作用,但编译器还不够复杂,无法弄清楚。

Suppress the warning with an annotation.使用注释抑制警告。

@SuppressWarnings("unchecked")
protected static <T> Parser<T> build(Class<T> parserType, InputArgGroup arguments) {
   // ...
}

Using this annotation is not circumventing the compiler - you got a warning and after analysis and running tests you verified the cast will never actually fail at runtime and you adding this annotation to record that analysis and finding.使用这个注解并没有绕过编译器——你得到一个警告,在分析和运行测试之后,你验证了强制转换在运行时永远不会失败,你添加这个注解来记录分析和发现。

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

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