2011-08-27 3 views
15

tôi sẽ rất nhiều chứ không phải muốn viết những dòng này:Compile lỗi: " '<>' không thể được sử dụng với các lớp nặc danh"

Lists.transform(vals, 
    new Function<>() { 
     public List<ValEntry> apply(Validator<? super T> input) { 
      return input.validate(value); 
     } 
    }); 

... hơn thế này:

Lists.transform(vals, 
    new Function<Validator<? super T>, List<ValEntry>>() { 
     public List<ValEntry> apply(Validator<? super T> input) { 
      return input.validate(value); 
     } 
    }); 

Nhưng Trình biên dịch Java cung cấp cho tôi thông báo lỗi sau:

'<>' cannot be used with anonymous classes 

Có lý do cơ bản nào cho điều này không? Hay đã bỏ qua tính năng trong JDK 7, có thể họ làm điều đó trong 8?

+1

Đừng chiến đấu với Java, nhảy tốt hơn với Scala ... – Landei

+3

Đôi khi trong cuộc sống, bạn không có lựa chọn nào khác để chiến đấu . – Lii

+1

Tôi không nhớ Java được thiết kế như một ngôn ngữ chức năng – Woot4Moo

Trả lời

14

Theo 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 Vì vậy, nó có thể trong một phiên bản tương lai. Nó vẫn không thể thực hiện được với Java 8, nhưng bây giờ chúng ta có lambdas, vì vậy có ít nhu cầu hơn.

+1

Cảm ơn bạn đã nghiên cứu. Nội bộ của generics và type suy luận là những điều thú vị nhưng phức tạp. – Lii

+4

Tôi vẫn chưa hiểu. Tại sao việc thêm một thân lớp vào một lời gọi hàm khởi tạo vô hiệu hóa toán tử kim cương từ việc suy ra các tham số kiểu? 'ArrayList a = new ArrayList <>();' là hợp lệ nhưng 'ArrayList a = new ArrayList <>() {};' thì không. Tham số kiểu khá rõ ràng 'Chuỗi'. Tại sao tệp lớp ẩn danh không thể nói như vậy? – thejoshwolfe

+0

Vẫn không thể với java 8 – gontard

3

này hiện đang dự kiến ​​sẽ được bao gồm trong Java 9. Từ JEP 213: Milling Project Coin:

  1. 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.