Refactoring capabilities in Eclipse

Source: Internet
Author: User
Tags object object static class

Refactoring capabilities in Eclipse

The refactoring feature in Eclipse makes it a modern Java integrated development environment (IDE) and is no longer a normal text editor. With refactoring, you can easily change your code without worrying about damaging it elsewhere. With refactoring, you can focus only on the functionality of the code you write, without distracting yourself from thinking about how your code looks, because you can then use refactoring tools to quickly turn code into neat, highly modular code. This article will show you how to use some of the most powerful refactoring functions in Eclipse.

Refactoring type

Renaming

Rename should be a heavily used refactoring in Eclipse. With this refactoring, you can rename variables, classes, methods, packages, folders, and almost any Java identifier. When an identifier is renamed, all references to that identifier are also renamed. The shortcut to call Rename refactoring is alt+shift+r. When you call this shortcut to an identifier in the Eclipse Editor, a small dialog box appears in the editor that allows you to modify the name of the identifier in this dialog box. When you press the Enter key, all references to the identifier are changed accordingly.

Move

With move, you can move a class from one package to another. This class is physically moved to the folder corresponding to the destination package, and all references to the class are changed to point to the new package.

If you drag a class into a new package in the Packages Explorer view, this refactoring will happen automatically.

Extract Local Variable

Using the Extract local Variable refactoring, you can assign the result of a Java expression to a new local variable. One use of this refactoring is to simplify the expression by dividing a complex Java expression into multiple lines. Or, when editing code, type this expression and use this refactoring to automatically create a new local variable to specify the result of the expression. This refactoring is useful when the type of the return value is complex, because the type of the variable is automatically generated.

This refactoring can be called from the editor. After you type the expression that you want to assign to a variable, press ctrl+1 and select Assign statement to a local variable. Such a new variable with the appropriate type is created.

Extract Constant

Extract Constant refactoring can convert any number or string literal in your code to a static final field (final field). After refactoring, all use of numbers or string literals in this class will point to the field instead of to the number or string literal itself. This allows you to modify all numbers or string literals in one place (the value of the field), without having to execute queries and overrides throughout the code.

To use this refactoring, select the number or string literal in the editor, then press ctrl+1 and select Extract to Constant.

Convert Local Variable to Field

As its name implies, this convert local Variable to field refactoring is able to get a local variable and convert that variable to a private field of this class. Thereafter, all references to this local variable will also point to the field.

To use this refactoring, select a local variable, then press ctrl+1 and select Convert local Variable to Field.

Convert Anonymous Class to Nested

Convert Anonymous class to Nested refactoring can accept an anonymous class and convert it to a nested class that initially contains the method of the anonymous class.

To use this refactoring, place your cursor in this anonymous class and choose Refactor > Convert Anonymous class to Nestedfrom the menu. A dialog box appears asking you to enter a name for the new class. In addition, you can set the properties of a class, such as specifying whether access to the class is public, protected, private, or default. You can also specify whether the class is end-state, static, or both.

For example, the code shown in Listing 1 uses an anonymous class to create a Thread Factory.


Listing 1. Before you perform the Convert Anonymous Class to Nested refactoring

void CreatePool () {threadPool = Executors.newfixedthreadpool (1, New Threadfactory () {@Overridepublic Thread newthread ( Runnable r) {Thread t = new Thread (r); T.setname ("Worker Thread"); t.setpriority (thread.min_priority); T.setdaemon (True) ; return t;});}

If this anonymous class can be placed separately as an inner class, the code in Listing 1 will be much more concise. Therefore, I perform the Convert Anonymous class to Nested refactoring and name the new class MyThreadFactory . The results are more concise, as shown in the code in Listing 2.


Listing 2. After you perform the Convert Anonymous Class to Nested refactoring

Private Final class Mythreadfactory implements threadfactory{@Overridepublic thread Newthread (Runnable r) {Thread t = new T Hread (R); T.setname ("Worker thread"), t.setpriority (thread.min_priority); T.setdaemon (true); return t;}} void CreatePool () {threadPool = Executors.newfixedthreadpool (1, New mythreadfactory ());}

Convert Member Type to Top level

Convert Member type to top level refactoring can accept a nested class and convert it to a top class that contains its own Java files.

To use this refactoring, place the cursor in a nested class and select Refactor > Convert Member Type to Toplevel. If the nested class is a static class, a box appears immediately, showing a preview of the refactoring. If it is not a static class, you need to first declare the name of the field that holds a reference to the parent class of this nested class before you can see the preview box. In addition, this field can be declared as an end state in this box.

Extract Interface

Extract Interface refactoring can generate an interface from a defined method of a class.

To use this refactoring, choose Refactor > Extract Interfacefrom the menu. A dialog box is displayed that asks for a new interface name. You can check those methods that come from this class and are declared within this interface. This dialog box also allows you to convert all valid references to this class to a reference to this interface. Note: This refactoring will only convert valid references to this class to the new interface type. This means that if a method in this class is not selected as part of the interface and Eclipse detects a reference to the class that uses the method, the reference will not be converted to the new interface type. Keep this in mind, and do not mistakenly assume that all references to this class will be converted to the new interface type.

Extract Superclass

Extract Superclass refactoring is similar to the Extract Interface refactoring described earlier. Just Extract superclass refactoring extracts a superclass rather than an interface. If the class already uses a superclass, the newly generated superclass will use the class as its superclass and maintain the class hierarchy.

To use this refactoring, make sure that the cursor is on the method declaration or field of the class, and then select Refactor > Extract superclass. A dialog box similar to Extract Interface appears, and you can name the new superclass in this dialog box and select the methods and fields to put in the superclass.

The biggest difference between extracting a superclass and extracting an interface is that the method placed in the superclass is actually moved there. Therefore, if any of these methods contain references to any of the fields in the original class, you will get a compilation error because they are not visible to the superclass. In this case, the best remedy is to move the referenced fields into the superclass as well.

Extract Method

Extract method Refactoring allows you to select a piece of code and convert it to a method. Eclipse automatically infer method parameters and return types.

This refactoring is useful if a method is too large and you want to divide the method into different ways. This refactoring can also be useful if there is a piece of code that is used repeatedly in many ways. When one of these code blocks is selected for refactoring, Eclipse will find another place where this block of code appears, replacing it with a call to the new method.

To use this refactoring, select a block of code in the editor and press Alt+shift+m. A dialog box appears asking you to enter the name and visibility of the new method (public, private, protected, or default). You can even change the parameters and return types. When the selected code block within the new method is refactored to properly use the parameters and return types of the new method, the new method is created. The first method to complete the refactoring now includes a call to the new method.

For example, suppose I want to map.get() move a block of code to another method after invoking listing 3.


Listing 3. Before Extract Method reconstruction

@Overridepublic object get (Object key) {Timedkey Timedkey = new Timedkey (System.currenttimemillis (), key), Object object = Map.get (Timedkey); if (Object! = null) {/** * If this is removed after the  ' get ' call by the worker thread * put it BAC K in */map.put (Timedkey, object); return object;} return null;}

To do this, select the code block in the editor and press Alt+shift+m. Set the name of the new method to putIfNotNull() , Eclipse generates the code in Listing 4, and automatically calculates the correct parameters and return values.


Listing 4. After the Extract Method is reconstructed

@Overridepublic object get (Object key) {Timedkey Timedkey = new Timedkey (System.currenttimemillis (), key), Object object = Map.get (Timedkey); return Putifnotnull (Timedkey, object);} Private Object Putifnotnull (Timedkey Timedkey, Object object) {if (Object! = null) {/** * If this is removed after the  ' Get ' call by the worker thread * put it back in */map.put (Timedkey, object); return object;} return null;}

Inline

Inline refactoring can inline a reference to a variable or method. When this refactoring is used, it replaces the reference to the variable or method with the value assigned to the variable or the implementation of this method. This refactoring is useful for cleaning up code in the following situations:

    • When a method is called only once by another method and is more meaningful as a block of code.
    • Compare a value to a different variable and divide the expression into multiple lines, placing an expression on one line and looking more neatly.

To use this refactoring, place the cursor over a variable or method and press Alt+shift+i. A dialog box appears asking you to confirm the refactoring. If you refactor a method, the dialog box also gives an option to delete the method after the refactoring is done.

For example, the second line in Listing 5 simply assigns the value of an expression to a timedKey variable.


Listing 5. Prior to Inline refactoring

public object put (object key, Object value) {Timedkey Timedkey = new Timedkey (System.currenttimemillis (), key), and return map. Put (timedkey, value);}

Listing 6 shows the code that performed the Inline refactoring. Note that the previous two lines of code now become a neat line of code.


Listing 6. After Inline refactoring

@Overridepublic object put (object key, object value) {return map.put (new Timedkey (System.currenttimemillis (), key), value);}

Change Method Signature

A method signature can be changed by using the Signature refactoring. It will also modify all calls to the method to use this new signature.

To use this refactoring, select Refactor > Change Method Signature. A 1 dialog box appears, where you can modify the method arbitrarily, including adding or removing parameters, changing the order of parameters, changing the type of the return value, adding exceptions to this method declaration, and even changing the name of the method.


Figure 1. Change Method Signature dialog box


Note that some modifications to this method, such as adding a parameter or changing a return type, may cause compilation errors in refactoring code, because Eclipse does not know what to enter for these new parameters.

Infer Generic Type Arguments

Infer Generic type Arguments refactoring automatically guesses the appropriate generic type (Generic type) for those classes in the original form. This refactoring is often used to convert the previous Java 5 code into Java 5 or later code.

This refactoring can even be called from the package Explorer. Just right-click any project, package, or class in the Packages Explorer and select Refactor > Infer Generic Type Arguments.

The code in Listing 7 shows one that can accept Generic Type Arguments ConcurrentHashMap . However, the code in Listing 7 does not specify a type parameter.


Listing 7. Infer Generic Type Arguments before refactoring

Private final Concurrenthashmap map = new Concurrenthashmap ();

After using the infer Generic type Arguments refactoring, Eclipse automatically determines the correct type parameters and generates the code in Listing 8.


Listing 8. Infer Generic Type Arguments after refactoring

Private final Concurrenthashmap map =      new Concurrenthashmap ();

Migrate JAR File

The Migrate JAR file refactoring can be used to easily update Java Archive (JAR) files on a project build path. To update the JAR files on the build path with a new version, the most common methods are:

    1. Enter the properties of the project and remove the existing JAR file from the build path.
    2. Manually remove the JAR file from its folder.
    3. Copy the new JAR file and rename it to reflect the name that was used when it was referenced in all the build scripts.
    4. Manually add a new JAR file to the build path.

However, with Migrate JAR File refactoring, the above work can be done in a single step. To invoke this refactoring, select Refactor > Migrate Jars. In the dialog box that appears, select the location where the new JAR file is located. In the following tree, select the JAR from the project that needs to be updated to the new version. If the Replace jar file contents But preserve existing filename check box is selected, the new Jar file is renamed to match the name of the old jar file, and therefore does not break any references to that name The build script for this JAR file. In any case, when you click Finish , the previous jar file will be deleted, and the new jar file will be copied to the location of the original jar file and will be automatically added to the project's build path so that the project can use the new jar file.

Refactoring scripts

Refactoring scripts allow you to export and share refactoring actions. Refactoring scripts are useful when you plan to publish a new version of a library and people will cause errors when using older versions. By publishing a refactoring script at the same time that the library is published, people who use the old version can simply apply the script to their project, allowing their code to use the new version of the library.

To create a refactoring script, select Refactor > Create Script. A 2 window appears, showing the history of all the refactoring performed in this workspace. Select the refactoring that you want, and then specify a location for the script that will be generated, and then click Create to generate the script.


Figure 2. Create Script window


To apply an existing refactoring script to the workspace, select Refactor > Apply script. In the dialog box that appears, select the location of the script. Click Next to see the refactoring that the script will perform, and then click Finish to apply the refactoring.

For example, suppose that in version 2 of a JAR file, the com.A class is renamed to com.B . Because people using the JAR file version 1 still have references to them in their code com.A , if they simply upgrade to a new version of the library, they will undoubtedly break their existing code. However, it is now possible to publish a refactoring script at the same time that the jar file is published, which automatically renames a reference to the com.A class as a reference to the pair com.B , so that people can easily upgrade to a new version of the jar file.

Conclusion

With a variety of refactoring in Eclipse, it's easy to transform ugly code into beautiful, graceful code. Refactoring scripts allow you to easily upgrade your application without worrying about how many hours a customer needs to navigate through the documentation to find out why the code is broken. Eclipse's refactoring capabilities are truly superior to other file editors and Ides.

Refactoring capabilities in Eclipse

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.