zappee
zappee

Reputation: 22668

Java generic: Unchecked cast

I must use 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:

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:

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

Parser 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.

Upvotes: 0

Views: 156

Answers (1)

Bohemian
Bohemian

Reputation: 424983

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. Anyone seeing this annotation should interpret it as a record of your analysis and finding.

Upvotes: 3

Related Questions