问题
I would so much rather like to write this:
Lists.transform(vals,
new Function<>() {
public List<ValEntry> apply(Validator<? super T> input) {
return input.validate(value);
}
});
...than this:
Lists.transform(vals,
new Function<Validator<? super T>, List<ValEntry>>() {
public List<ValEntry> apply(Validator<? super T> input) {
return input.validate( value );
}
});
But the Java compiler gives me the following error message:
'<>' cannot be used with anonymous classes
Is there a fundamental reason for this? Or did the just skip the feature in JDK 7, maybe they do it in 8?
回答1:
According to the project coin documentation:
Internally, a Java compiler operates over a richer set of types than those that can be written down explicitly in a Java program. The compiler-internal types which cannot be written in a Java program are called non-denotable types. Non-denotable types can occur as the result of the inference used by diamond. Therefore, using diamond with anonymous inner classes is not supported since doing so in general would require extensions to the class file signature attribute to represent non-denotable types, a de facto JVM change. It is feasible that future platform versions could allow use of diamond when creating an anonymous inner class as long as the inferred type was denotable.
EDIT So it's possible in a future version. It's still not possible with Java 8, but now we have lambdas, so there's less of a need.
回答2:
This is now scheduled to be included in Java 9. From JEP 213: Milling Project Coin:
- Allow diamond with anonymous classes if the argument type of the inferred type is denotable. Because the inferred type using diamond with an anonymous class constructor could be outside of the set of types supported by the signature attribute, using diamond with anonymous classes was disallowed in Java SE 7. As noted in the JSR 334 proposed final draft, it would be possible to ease this restriction if the inferred type was denotable.
来源:https://stackoverflow.com/questions/7214069/compile-error-cannot-be-used-with-anonymous-classes