如何避免通用警告

问题描述 投票:-7回答:1
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定义的子类

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;
}

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

java generics
1个回答
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.