使用java检查器框架,为什么Nonvalues不被接受到Nullable值位置?

ryevplcw  于 4个月前  发布在  Java
关注(0)|答案(1)|浏览(49)

使用java检查器框架,为什么Map Nonvalues不被接受到Map Nullable value位置?
使用此代码调用:

schema.validate(
            MapMaker.makeMap(
                new AbstractMap.SimpleEntry<>(
                    "foo",
                    "baz"
                ),
                new AbstractMap.SimpleEntry<>(
                    "bar",
                    2
                )
            ),
            configuration
        );

字符串
我得到这个错误:

java: [argument] incompatible argument for parameter arg of validate.
  found   : @Initialized @NonNull Map<@Initialized @NonNull String, @Initialized @NonNull Object>
  required: @Initialized @NonNull Map<@Initialized @NonNull String, @Initialized @Nullable Object>


验证方法定义为:public FrozenMap<@Nullable Object> validate(Map<String, @Nullable Object> arg, SchemaConfiguration configuration) throws ValidationException, InvalidTypeException {
任何非空的Object都是可空的Object集合的子集,那么为什么这不起作用呢?我如何让它对不可空的key输入也起作用呢?我需要为可空和不可空的input arg使用不同的输入法签名吗?
我传递给validate方法的参数将仅用于阅读。根据检查器框架javadocs,@Covariant可能是这里的一个解决方案:For example, consider Iterator. A client can read elements but not write them, so Iterator<@Nullable String> can be a subtype of Iterator<String> without introducing a hole in the type system. Therefore, its type parameter is annotated with @Covariant. The first type parameter of Map.Entry is also covariant. Another example would be the type parameter of a hypothetical class ImmutableList.
但这只适用于接口。

mccptt67

mccptt671#

所以这是因为检查器框架看到了

  • 字符串
  • @Nullable String作为两个不同的类,其中String(@ NonString)继承自@Nullable string。

所以这里的解决方案是:
1.使用扩展来允许协方差,如public FrozenMap<@Nullable Object> validate(Map<String, ? extends @Nullable Object> arg, SchemaConfiguration configuration) throws ValidationException, InvalidTypeException {
1.更新validate方法以接受Map<String, ?>这不是很好,因为签名中的类型检查信息丢失了
1.或者编写许多方法,接受所有带/不带@Nullable的组合,如Map<String, @Nullable Object> argMap<String, Object> arg
1.或者编写一个接口,为每个可空参数生成一个泛型参数,并实现它。
第4个示例代码如下所示

@Covariant(0)
public interface MapValidator <InType extends @Nullable Object, OutType> {
    OutType validate(Map<String, InType> arg, SchemaConfiguration configuration) throws ValidationException, InvalidTypeException;
}

public class SomeSchema implements MapValidator<@Nullable Object, FrozenMap<@Nullable Object>> {
    OutType validate(Map<String, @Nullable Object> arg, SchemaConfiguration configuration) throws ValidationException, InvalidTypeException {
        ...
    }

}

字符串

相关问题