【问题标题】:How can I avoid the generic warning如何避免通用警告
【发布时间】:2019-02-21 03:47:13
【问题描述】:
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)

格式化程序是格式化程序的子类,定义如下

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

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

【问题讨论】:

  • 邮政编码作为文本,而不是作为图像。
  • 警告是什么?
  • 这个方法有什么用?为什么你一方面使用泛型,然后这样做Object-Object-mapping 放弃所有类型安全?
  • @luk2302 其实我找不到通用的方法来定义格式方法。

标签: java generics


【解决方案1】:

使静态方法也通用:

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

【讨论】:

  • 我试过这个,当我调用方法时我必须带类型参数。但是我不想(或者说我不能)在调用这个方法时使用任何类型参数。我在我的问题之后添加了调用代码。
猜你喜欢
  • 2016-12-25
  • 2021-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 2014-03-21
  • 2014-10-23
  • 1970-01-01
相关资源
最近更新 更多