Java generic support in eclipse 3.1

Source: Internet
Author: User
Java 5 provides generic support, which is a feature required by developers for many years. It represents an important upgrade of the Java programming language. Complex technologies such as generics pose challenges not only to tool vendors but also to developers. This article focuses on how eclipse handles the challenges of generics and the changes that generics bring to the Java language, and shows how to make full use of generics in eclipse, including support for quick help, Quick repair, refactoring, and project parameter selection. In addition, it also shows some subtle and important aspects of fully generic languages.

  Generics in Java

Almost beginning with the first version, Java technology creators have begun to discuss how to add generic support for the language. C ++ supports generics through the standard template library. However, due to the lack of a uniform parent class for all other classes (object classes embedded in the Java language, the implementation of generics is also hindered. The generic support of the Java programming language is the most significant syntactic change in its history. For some obvious reasons, tool support is much slower than other SDK upgrade steps. Even so, eclipse v3.1 now has excellent support for the new features of these languages. This article focuses on some of the new features.

  Java 5 Project

To enable the Java generic support in eclipse v3.1, you need to install Java 5 on the machine and download it from some common places to Java 5. Generics can be displayed on the compiler settings page along with project properties. This means that, as before, each project has its own SDK settings. To create a project that uses generics, you must specify the language level when creating a project or use the project properties of an existing project to specify the language level.

Java 5 uses two specific property pages. The first property page specifies compiler settings.

Figure 1. compiler-specific settings supported by Java 5

420) {This. resized = true; this. style. width = 420;} "resized =" true ">

Unless you have set the default Project Settings in eclipse for Java 5, you must overwrite those settings for the project. The JDK compliance area allows you to set source files and class files. When you set the source file to level 5.0, you will get a lot of new content help and refactoring options.

Another related Property dialog box is the errors/warnings area in the Tree View.

Figure 2. Errors/warnings area of Project Properties

420) {This. resized = true; this. style. width = 420;} "resized =" true ">

A large number of j2se 5 options can control what types of errors and warnings eclipse generates for your Java 5 code (see Table 1)

Table 1. Errors and warnings generated by eclipse for Java 5 code
J2se 5 Option Warning type
Unchecked generic type operation The compiler sends an error or warning every time it encounters an unchecked generic type operation. This operation includes operations of the list or arraylist type, but does not specify the type. Every time you use an old collection class that saves objects, a warning is generated.
Generic Type parameter declared with a final type bound The compiler sends an error or warning whenever it encounters a Type Binding involving the final type. Please refer to the example method signature:
Public int doit (list <? Extends string> List)

Because string is of the final type and the parameter cannot be extended, this write is more effective:
Public int doit (list <string> List)

Inexact type match for vararg arguments When the compiler cannot determine the developer's intent from the varargs parameter, it generates a warning. Some varargs related to arrays are ambiguous.
Boxing and unboxing Conversions Alert the automatic packing operation (the packing operation may affect the performance), and do not assume the object identity for the type packaging object. This is a small warning that is ignored by default.
Missing @ override Annotation The @ override comment should be included for any override method. The absence of this comment may indicate that the developer is not aware that the method is overwritten.
Missing @ deprecated Annotation Warning generated because the @ deprecated flag is missing.
Annotation is used as super Interface You cannot use the deprecated class as a super interface. For example, this method is not recommended:
Public interface badform extends deprecated {

}
.

Not all Enum constants covered on Switch If the switch statement lacks enumeration items, you may miss some enumeration options.
Unhandled warning tokens in @ suppresswarnings Java 5 allows you to add comments to suppress compiler warnings. If you have misspelled a warning or used a warning that does not exist, this flag sends a warning.
Enable @ suppresswarnings annotations Open the program (using code) to suppress warnings that you don't care about.

Once you set all the project options according to your preferences, you can start to use generics in eclipse.

Three pages in total. 1 2 38:    Transition from a specific type to a generic type

Consider the simple class in Listing 1. It creates a list of employee and manager objects (Manager extended from employee), prints them out, and prints them out after raising their salary.

List 1. HR class

  package com.nealford.devworks.generics.generics;  import java.util.ArrayList;  import java.util.Collections;  import java.util.List;  public class HR {      public HR() {          List empList = new ArrayList(5);          empList.add(new Employee("Homer", 200.0, 1995));          empList.add(new Employee("Lenny", 300.0, 2000));          empList.add(new Employee("Waylon", 700.0, 1965));          empList.add(new Manager("Monty", 2000.0, 1933,                   (Employee) empList.get(2)));                    printEmployees(empList);                    System.out.println("----- Give everyone a raise -----");          for (int i = 0; i < empList.size(); i++)              ((Employee) empList.get(i)).applyRaise(5);                    printEmployees(empList);                    System.out.println("The maximum salary for any employee is "+                  Employee.MAX_SALARY);                    System.out.println("Sort employees by salary");          Collections.sort(empList);          printEmployees(empList);                    System.out.println("Sort employees by name");          Collections.sort(empList, new Employee.NameComparer());          printEmployees(empList);                    System.out.println("Sort employees by hire year");          Collections.sort(empList, Employee.getHireYearComparator());          printEmployees(empList);      }            public void printEmployees(List emps) {          for (int i = 0; i < emps.size(); i++)               System.out.println(emps.get(i));      }            public static void main(String[] args) {          new HR();      }  }

If you enable Java 5 support, multiple warning messages will appear when compiling this code.

  Quick Recovery features

Whenever eclipse suggests an improvement to your code, the quick fix feature of eclipse is displayed as a light bulb on the left sidebar of the editor window. In the code in Listing 1, you will see multiple quick fixes.

Figure 3. Quick Fix lightbulb indicates your code to be improved

420) {This. resized = true; this. style. width = 420;} "resized =" true ">

Quick fixes use bulbs and yellow wavy lines to indicate improvements to be made. If you move your mouse over the yellow wave line, you can see the improvement suggestions shown in Figure 4.

Figure 4. Quick Fix indicates what should be generalized

420) {This. resized = true; this. style. width = 420;} "resized =" true ">

There is only one quick fix suggestion listed here. We recommend that you add a local variable to save the return value of the add () method of the list. However, this method returns a Boolean value and is ignored.

To locate the quick fix suggestion, move to the refactoring menu. Many refactoring in eclipse is directly related to the generics in Java 5. "Infer generic type arguments" refactoring adds generic support to the list. The first dialog box allows you to select options.

Figure 5. infer generic type arguments choices dialog box

420) {This. resized = true; this. style. width = 420;} "resized =" true ">

The first option is related to a conclusion. The conclusion is that the clone () method will return the receiver type rather than the other type (related class ). Most classes with good functions follow this rule. If you know that your class does not comply with this rule, do not select this option. If the second option is not selected, the "Raw" (non-generic) parameter is retained, rather than the correct generic parameter type.

In most refactoring in eclipse, You can preview what changes will happen to your class. Click the preview button in the dialog box to display the dialog box shown in figure 6.

Figure 6. preview the generic refactoring

0 recommended

420) {This. resized = true; this. style. width = 420;} "resized =" true ">

 

The updated code is as follows:

Listing 2. Updated code

  List<Employee> empList = new ArrayList<Employee>(5);  empList.add(new Employee("Homer", 200.0, 1995));  empList.add(new Employee("Lenny", 300.0, 2000));  empList.add(new Employee("Waylon", 700.0, 1965));  empList.add(new Manager("Monty", 2000.0, 1933, empList.get(2)));  

Two interesting changes have taken place in the code. First -- and most obvious -- list and arraylist declarations are now generic types of the employee type. Second-not obvious-changes in the last line of the Code. Observe how the original emplist of the manager class is added. The last parameter of the manager class must be forcibly converted to employee for the assistant domain. Infer refactoring is smart enough to delete unnecessary type forced conversions.

Before the quick fix is introduced, eclipse also adds another interesting aspect to Java 5 support: You can get suggestions for adding annotations to methods, such as @ override. You can also help with comments.

Figure 7. quick fix for comments and content help extension

420) {This. resized = true; this. style. width = 420;} "resized =" true ">

  Quick help features

Eclipse v3.1 has added quick help to facilitate generic support in Java 5. Consider this common for () loop. See the printemployees () method in listing 3.

Listing 3. For () loop

  public void printEmployees(List<Employee> emps) {      for (int i = 0; i < emps.size(); i++)           System.out.println(emps.get(i));  }  

In addition to the support for generics, Java 5 now supports the for... each loop. We recommend that you change the for loop to for... each. The changed code is shown in Listing 4.

Listing 4. For... each loop

  public void printEmployees(List<Employee> emps) {      for (Employee emp : emps)           System.out.println(emp);  }  

This version is much cleaner because I variables and get () method calls are completely deleted.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.