如何避免通用警告

时间:2018-09-17 08:52:32

标签: java generics

public abstract class Formatter<P, R> {

    public static Object format(Object src, Class<? extends Formatter> formatter) {

        Formatter fmt;
        try {
            fmt = formatter.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        return fmt.format(src);  // Unchecked call warning here
    }

    public abstract R format(P src);

}

如何避免调用时出现通用警告

fmt.format(src)

formatter是Formatter的子类,其定义类似于

PhoneFormatter extends Formatter<String, String>

这是调用代码

if (annotation instanceof LogFormat) {
    LogFormat logFormat = (LogFormat) annotation;
    arg = Formatter.format(arg, logFormat.formatter());
}

-

public class User {

    @LogFormat(formatter = PhoneNumberFormatter.class)
    private String mobile;
}

我不想(或者说我不能)使用任何类型参数来调用此方法。

1 个答案:

答案 0 :(得分:0)

也使静态方法通用:

abstract class Formatter <P, R> {
    static <P, R> R format(P src, Class<? extends Formatter <P, R>> formatter) {
        Formatter <P, R> fmt;
        try {
            fmt = formatter.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return fmt.format(src);
    }

    abstract R format(P r);
}