1

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.

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?

ekaqu
  • 2,038
  • 3
  • 24
  • 38
  • in my OCPJ6P studies, the only point that got me confused is mixing between Generics and statics, i didnt understand this point well, but what i understood at the end is that Generics cant be mixed with static (methods or variables), since statics are present in memory before compile time, and Generics depend on Compile time, try this code in a non-static code – Ahmed Adel Ismail Sep 06 '13 at 20:57
  • @EL-conteDe-monteTereBentikh That won't be necessary - see my answer. – Paul Bellora Sep 06 '13 at 21:01

1 Answers1

3

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.

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;
Community
  • 1
  • 1
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181