Đang chuẩn bị liên kết để tải về tài liệu:
Programming Groovy dynamic productivity for the java developer phần 3
Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Bạn có thể mong đợi tính năng này trong Groovy khi nó hỗ trợ các lớp bên trong. Nếu bạn cần để ghi đè lên các phương pháp cho các giá trị enum cụ thể ngay bây giờ, bạn có thể sử dụng một cách giải quyết. Tiêm phương pháp vào các ví dụ mà bạn mong muốn bằng cách sử dụng ExpandoMetaClass, 16 như đưa ra ở đây | Support of Java 5 Language Features 63 You can expect this feature in Groovy when it supports inner classes. If you need to override methods for specific enum values right now you can use a workaround. Inject the method into the instance you desire using ExpandoMetaClass 16 as shown here Download GroovyForJavaEyes ActivityWorkaround.groovy enum WeekendActivity SATURDAY SUNDAY String activity Relax def emc new ExpandoMetaClass WeekendActivity emc.activity - Play emc.initialize WeekendActivity.SATURDAY.metaClass emc for day in WeekendActivity.values printin day - day.activity The output from the previous code is as follows SATURDAY - Play SUNDAY - Relax varargs Remember Java 5 varargs allows you to pass a variable number of arguments to methods such as the printf method. To use this feature in Java you mark the trailing parameter type of a method with an ellipsis as in public static Object max Object. args . This is syntactic sugar Java rolls all the arguments into an array at the time of call. Groovy supports Java 5 varargs in two different ways. Groovy s support for varargs is even available with Java 1.4. In addition to supporting parameters marked with . you can pass variable arguments to methods that accept an array as a trailing parameter. 16. You ll learn about method injection and ExpandoMetaClass later in Chapter 14 MOP Method Injection and Synthesis on page 202. Support of Java 5 Language Features 64 Let s look at a Groovy example for these two ways Download GroovyForJavaEyes VarArgs.groovy def foo1 int a int. b printin You passed a and b def foo2 int a int b printin You passed a and b foo1 1 2 3 4 5 foo2 1 2 3 4 5 The output from the previous code is as follows You passed 1 and 2 3 4 5 You passed 1 and 2 3 4 5 You can send either an array or discrete values to methods that accept varargs or an array as trailing parameters and Groovy figures out what to do. Annotations Annotations in Java allows you to express metadata and Java 5 ships with a few predefined