简体   繁体   English

Java泛型和强制转换泛型类型

[英]Java generics and casting a generic type

I am trying to use guava to create a comparable where I only care about a single field of a class (used by a collection for sorting). 我试图用番石榴来创建一个可比较的地方,我只在乎一个类的单个字段(由集合用于排序)。 This field is generic and can take any type. 此字段是通用字段,可以采用任何类型。 I am using guava's Ordering#onResultOf method to convert the wrapper object into the generic type, and provide a comparable for that type. 我正在使用番石榴的Ordering#on​​ResultOf方法将包装器对象转换为通用类型,并为该类型提供可比较的对象。

I have the following code: 我有以下代码:

  private static final class Reference<T> { ... }
  ...
  public static <T> Function<Reference<T>, T> referenceToData() {
    return (Function<Reference<T>, T>) ToData.INSTANCE;
  }

  private enum ToData implements Function<Reference<Object>, Object> {
    INSTANCE;

    @Override
    public Object apply(final ComparatorMerger.Reference<Object> input) {
      return input.data;
    }
  }

When I compile the code I get the following error: 当我编译代码时,出现以下错误:

[ERROR] ... inconvertible types
[ERROR] found   : Reference.ToData
[ERROR] required: com.google.common.base.Function<Reference<T>,T>

I am not sure how to get the casting to work the way I want it to. 我不确定如何使演员按照我想要的方式工作。 Any advice? 有什么建议吗?

You need to do a double cast: 您需要进行两次强制转换:

return (Function<Reference<T>, T>)(Function<?, ?>)ToData.INSTANCE;

See also my recent answer using this pattern (from Joshua Bloch's Effective Java item 27, "favor generic methods") as an example of a valid unchecked cast. 另请参阅我最近使用此模式的答案 (来自Joshua Bloch的Effective Java项目27,“偏爱的通用方法”),作为有效的未经检查的强制转换的示例。

As I point out there, you should also consider suppressing the unchecked cast warning: 正如我指出的那样,您还应该考虑取消未经检查的强制转换警告:

@SuppressWarnings("unchecked") // this is safe for any T
final Function<Reference<T>, T> withNarrowedTypes =
        (Function<Reference<T>, T>)(Function<?, ?>)ToData.INSTANCE;
return withNarrowedTypes;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM