Trying to create a static field with a generic type doesn’t compile:
class MyClass {
public static Function<Z, Z> blargh = new Function<Z, Z>() {
public Z apply(Z a) {
return a;
}
};
}
Eclipse says:
Multiple markers at this line
- Z cannot be resolved to a type
- Z cannot be resolved to a type
- Z cannot be resolved to a type
- Z cannot be resolved to a type
- The type new Function<Z,Z>(){} must implement the inherited
abstract method Function<Z,Z>.apply(Z)
but replacing all the Zs with a concrete type works just fine:
static Function<Integer, Integer> blargh = new Function<Integer, Integer>() {
public Integer apply(Integer a) {
return a;
}
};
What’s going on here?
Context:
-
I was originally trying to figure out why this code uses a method instead of a field:
public static <T extends Throwable> F<T, String> eMessage() { return new F<T, String>() { public String f(final Throwable t) { return t.getMessage(); } }; }Maybe it’s to overcome this restriction?
-
the
Functiontype is from Google’s guava library.
Edit: Now I see the problem better.
I think that firstly you would have to declare the type as a class parameter:
to get visibility, but now the reason you can’t use it like that is because the static member should be shared among all the instances of the class. But since you could create instances with different type parameters, the static member depending on a particular type would not make sense.