Refactoring is an editing technique that modifies code structure without altering program behavior. Refactoring is useful when you want to modify a program's source code to make it easier to maintain, extend, or reuse.
This chapter includes the following sections:
In most cases, you use the Java Source Editor to write or edit Java code. It contains a set of Java-specific features to enhance your coding experience. For example, JDeveloper makes it easy to code using predefined code templates, add Javadoc comments, and even apply formatting to your code. These features are available through the context menu and the Source main menu. For more information, see Using the Source Editor.
You can customize the behavior of the Java Source Editor by specifying preferences in the Preferences Dialog. For more information, see How to Set Preferences for the Source Editor.
JDeveloper provides many Java-aware editing features that you can use to improve your productivity. These include features for locating and moving to the source code for your projects' classes and interfaces and their members. JDeveloper also comes with keyboard accelerators to step from member to member in a class definition in the Java Source Editor.
While working in JDeveloper, you can browse Java elements using a JDeveloper dialog or directly from an open file in the Java Source Editor. You also can locate source code or Javadoc for a given type.
Sources are displayed for classes present in the project's source path. They are also displayed for classes present in a project library, if the library has sources included.
You can browse Java elements in the JDeveloper dialog shown in Figure 8-1:
Figure 8-1 Go to Java Type Dialog
To browse a Java element in JDeveloper:
When working in the Java Source Editor, you can quickly locate the declaration of any identifier.
To navigate to the declaration of a code element:
Right-click on the code element and choose Go to Declaration, or:
Press the Control key and left-click on the code element.
The source code for that element opens, with the line on which it is declared highlighted.
Figure 8-2 Highlighted Declaration
If the declaration is in the same file, the cursor moves to it and highlights it. If the declaration is in a different file, the source file opens in the Java Source Editor. The cursor moves to it and highlights it.
While working in the Java Source Editor, you can quickly locate references to a class or interface and its members. By default, usages in the current project and its dependency projects are reported. You can extend the search to libraries if the source files for the libraries are accessible.
To find the usages of a class:
While working in the Java Source Editor, you can quickly locate references to a method.
The search displays applications of the method to instances of the class or interface for which the method is defined. It also shows applications for instances of its subclasses or subinterfaces, if any, that inherit the method.
To find the usages of a method:
While working in the Java Source Editor, you can quickly locate references to a field.
The search shows references to the field in instances of the class or interface for which the field is defined. It also shows references for instances of its subclasses or subinterfaces, if any, that inherit the field.
To find the usages of a field:
While working in the Java Source Editor, you can quickly locate references to a local variable or a parameter in a method body. Local variables and parameters used in extracted code become parameters of the new method.
To find the usages of a local variable or parameter:
While working in the Java Source Editor, you can identify methods that override or implement superclass definitions. Overriding definitions are marked with the Overrides up arrow icon, as shown in Figure 8-3.
Figure 8-3 Overrides Icon
Overridden definitions are marked with the Implements margin icon in the Java Source Editor margin, as shown in Figure 8-4.
Figure 8-4 Implements Icon
To view the overridden definition of a method, click the Overrides margin icon. To view the overridden definition of a method, click the Implements margin icon.
Click the Back button on the Main toolbar to return to the previous view.
While working in the Java Source Editor, you can inspect the hierarchy of subtypes and supertypes of a class or interface.
What displays in the editor is the entire GUI hierarchy for the node. The method of display depends upon whether this hierarchy consists of menu or non-menu items.
You can use keyboard accelerators to step from member to member in a class definition in a Java Source Editor:
To step to the next member definition or declaration in the current Java source view, press Alt+Down, or choose Navigate > Go To Next Member.
To step to the previous member definition or declaration in the current Java source view, press Alt+Up, or choose Navigate, then Go To Previous Member.
The following code-stepping commands are also defined but are not assigned default accelerators and are not available through the Navigate menu:
Go to Next Class
Go to Next Field
Go to Next Method
Go to Previous Class
Go to Previous Field
Go to Previous Method
You can find these commands listed in the Navigate category of the Shortcut Keys page of the Preferences dialog. You can add or change accelerators. For more information, see How to Work with Shortcut Keys in the IDE.
JDeveloper provides many Java-aware editing features you can use to improve your productivity. As an alternative to text editing, you can also use the Java Visual Editor when developing graphical user interfaces. The Source Editor and Visual Editor are synchronized; a change in one is immediately reflected in the other. These Java editing features augment generic source editing features that support coding in any technology.
Before creating a new class or interface, you must first create an application and a project. After you create the class or interface, it is added to the active project and, by default, displays in the Java Source Editor. You can also access it in the Applications window.
To create a new class and add it to a project:
In the source editor, you can quickly add framework code to modify a target class to implement an interface or to make a target interface extend another interface.
An implements
or extends
clause is added to the declaration for the target class or interface, and an import statement is added to the file. If the target is a class, stub definitions for the implemented interface's methods are appended to the class or interface body.
To implement an interface:
In the source editor, you can quickly add stub definitions to a class to override methods inherited from superclasses. An overriding subclass provides a specific implementation of a method that is already provided by one of its superclasses.
To override methods:
Lambda expressions enable you to simplify coding by providing a mechanism for expressing instances of anonymous inner classes that contain only a single method in more compact forms. You can only convert such a class only if it meets the requirement of being a functional interface, that is one whose type can be used for a method parameter when a lambda expression is used as the argument to the method.
Note:
This feature is only accessible if you have specified JDK 1.8 as the target JDK for your project.
To convert an inner class to a lambda expression:
In the Java source editor, select the anonymous class to convert.
The IDE analyzes the code to check if code assist is applicable.
Click the code assist icon that appears in the editor margin.
Click the code assist Convert Anonymous Inner Class to a Lambda Expression.
The lambda expression replaces the inner class.
For more information, see http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
You can turn this feature on or off in the Preferences dialog. Note that this feature is on by default.
To turn this feature off:
JDeveloper provides predefined code templates that assist you in writing code more quickly and efficiently by inserting text for commonly used statements. For example, the "Iterate over a list" (itli
) template inserts the following code:
for (Object object : Object) { ; }
Note:
If the template contains variables, the variables are highlighted. You can edit each variable to complete the template. Pressing Tab moves the caret to the next template variable.
You can use shortcuts to speed up the selection of the required template. Pressing Ctrl+Enter anywhere in the source file brings up a list of code templates that you can select. The templates provided in this list are contextual and only those suitable for the current location are offered. You can click QuickDoc on the bottom right corner of this list to see the structure of the selected code template. If you were using the existing template for the for
loop, for instance, you would type for
and then (in the default keymapping) press Ctrl+Enter.
In addition to the templates provided by JDeveloper, you can also define your own code templates in the Code Editor - Code Templates page of the Preferences dialog. For more information, see How to Customize Code Templates for the Source Editor.
To evoke a defined code template:
Note:
Ctrl+Enter is the accelerator assigned in the default keymap. You can assign an alternative.
The predefined code templates that JDeveloper provides are shown below.
Array Iterator
ai for (int $i$ = 0; $i$ < $array$.length; $i$++) { $type$ $var$ = $array$[$i$]; $end$ }
Data Action Event Handler
daev public void on$end$(PageLifecycleContext ctx) { }
for loop
for for ($end$ ; ; ) { }
if statement
if if ($end$) { }
if else statement
ife if ($end$) { } else { }
integer based loop
fori for (int $i$ = 0; $i$ < $lim$; $i$++) { $end$ }
integer based loop
forn int $n$ = $lim$; for (int $i$ = 0; $i$ < $n$; $i$++) { $end$ }
instanceof + cast
iofc if ($var$ instanceof $type$) { $type$ $casted$ = ($type$) $var$; $end$ }
Instantiate a BC4J application module
String amDef = "test.TestModule"; String config = "TestModuleLocal"; ApplicationModule am = Configuration.createRootApplicationModule(amDef,config); ViewObject vo = am.findViewObject("TestView"); $end$// Work with your appmodule and view object here Configuration.releaseRootApplicationModule(am,true);
Iterate over array
itar for (int $i$ = 0; $i$ < $array$.length; $i$++) { $type$ $var$ = $array$[$i$]; $end$ }
Iterate over a collection
itco for(Iterator $iter$ = $col$.iterator();$iter$.hasNext();) { $type$ $var$ = ($type$) $iter$.next(); $end$ }
Iterate over a list
itli for (int $i$ = 0; $i$ < $list$.size(); $i$++) { $type$ $var$ = ($type$) $list$.get($i$); $end$ }
Iterate over map keys
itmk Iterator $iter$ = $map$.keySet().iterator(); while ($iter$.hasNext()) { $type$ $var$ = ($type$) $iter$.next(); $end$ }
Iterate over map values
itmv Iterator $iter$ = $map$.values().iterator(); while ($iter$.hasNext()) { $type$ $var$ = ($type$) $iter$.next(); $end$ }
JDBC Connection
conn public static Connection getConnection() throws SQLException { String username = "$end$scott"; String password = "tiger"; String thinConn = "jdbc:oracle:thin:@localhost:1521:ORCL"; Driver d = new OracleDriver(); Connection conn = DriverManager.getConnection(thinConn,username,password); conn.setAutoCommit(false); return conn; }
List to array
ltoar $type$ $var$ = new $typeelem$[$list$.size()]; $var$ = ($type$) $list$.toArray($var$); $end$
main method
main public static void main(String[] args) { $end$ }
out.println()
outp out.println($end$);
private ArrayList
pral private ArrayList _$end$ = new ArrayList();
private boolean
prb private boolean _$end$;
private HashMap
prhm private HashMap _$end$ = new HashMap();
private int
pri private int _$end$;
private String
prs private String _$end$;
public static final
pusf public static final $end$;
public static final boolean
pusfb public static final boolean $end$;
public static final int
pusfi public static final int $end$;
public static final String
pusfs public static final String $end$;
Reverse array iterator
ritar for (int $i$ = $array$.length; --$i$ >= 0 ;) { $type$ $var$ = $array$[$i$]; $end$ }
Reverse iteration over a list
ritli for (int $i$ = $list$.size(); --$i$ >= 0 ; ) { $type$ $var$ = ($type$) $list$.get($i$); $end$ }
System.err.println
sep System.err.println($end$);
System.out.println
sop System.out.println($end$);
switch statement
sw switch ($end$) { case XXX: { } break; default; { } break; }
try statement
try try { $end$ } catch (Exception ex) { ex.printStackTrace(); } finally { }
Insert a tag
tag <$tag$> $end$ </$tag$>
while statement
wh while ($end$) { }
You can use the Expand/Narrow Selection option to successively expand or narrow a selected block of code, based on Java syntax. With each successive application of the option, the selection expands to include the next logical step up in the Java hierarchy, based on the starting point, until the entire file is selected. For example: method name, qualified method call, assignment, definition, and so on.
To expand selected code:
Use the Narrow Selection option (or press Ctrl+Shift+Minus) to successively reduce selected code in the same fashion.
You can easily surround Java statements and blocks with coding constructs in the Java Source Editor.
To surround a block of code with a construct:
Code constructs can be set using the Code Templates page of the Preferences dialog. You can customize code templates as needed or modify existing ones. For more information, see How to Customize Code Templates for the Source Editor.
You can use code folding to hide and display sections of a file currently open in the Java Source Editor. Code folding can improve readability, letting you view specific areas by folding selected blocks of code, such as function definitions.
To use code folding:
Click on the - sign to the left of the first column of text in the JavaScript editor.
This folds the code in the selected element, and changes the - sign to a +.
Click on the + sign to unfold the code, displaying the full contents of the area you previously folded.
Right-click between the signs in the margin to open a context menu from which you can select commands to expand or collapse specific areas of code throughout the entire file.
If you have code inside a method such as that shown below, you can collapse the middle chunk of code so you do not have to see it when working on another part of the method.
public void main(String[] args) throws SQLException, IOException { //... some code ... { Run.dbgPrnt("Extractor main() querying => BSN"); // make the basin file query = "select * from BSN"; rset = OracleAccess.makeResultSet(query, stmt); rset.next(); l = Basin.extract(rset, Version); Format.writeFile(outPath, "groupings.txt", l); } // ... some more code ... Run.dbgPrnt("Extractor main() has ended"); }
You can fold code for inner code blocks such as for, while, switch, {...}, etc.
You can add needed import statements while working in the Java Source Editor. If, as you are typing in the Source Editor, you introduce a reference to a class that has not yet been imported, a ragged line will appear below it. A popup will open showing that an import is needed, giving the fully-qualified name of the class.
Figure 8-5 Import Statement Needed
JDeveloper automatically adds an import if it can find only one exact match for an unresolved reference to a class. If the import assistance matches more than one possible match, then a popup list displays all possible matches from the class path. You can then choose the appropriate import and the import statement is automatically added.
The import assistance popup can be triggered at any time by pressing Alt+Enter.
The gutter-based code assistance can be used to add an import statement. If the editor does not recognize a class, a light bulb appears in the gutter when the line is highlighted and various import options are displayed.
To configure or disable Import assistance, you can set Import Statement Options in the Java Source Editor.
You can organize import statements easily in the Java Source Editor. Set the options for organizing imports in the Preferences dialog. The following options are provided:
Sort and group the import statements alphabetically by package and class name.
Narrow the imports by replacing type-import-on-demand statements for packages with single-type-import statements for individual classes.
Widen the imports by replacing two or more single-type-import statements for classes from a common package with a single type-import-on-demand statement for the package.
Remove import statements for classes that are not referenced.
You can configure or disable import organizing options.
To organize import statements in a source file:
With the file open in the editor, right-click and choose Organize Imports.
ojformat is a command line tool that you can use to reformat workspaces or projects. It is located in <JDeveloper_Home>/jdev/bin
.
The syntax for ojformat is
ojformat option file
where
option is an option such as -ade
. -ade
indicates that ADE extension for version control should be loaded. Other version controls should work automatically.
Examples
ojformat -ade application.jws
Reformats all projects in application.jws. Version control is ADE.
ojformat application1.jws application2.jws
Reformats all the projects in both applications
ojformat application.jws project1.jpr
Reformats project1.jpr
of application.jws
ojformat app1.jws project1.jpr app2.jws project2.jpr
Reformats project1 of app1 and project2 of app2
The Java Visual Editor displays the visual components of a user interface in the Design tab, as shown in Figure 8-6.
Figure 8-6 Java Visual Editor Design View
You see the Java source view of the visual classes by clicking the Source tab as shown in Figure 8-7.
Figure 8-7 Java Visual Editor Source View
When the Java Visual Editor is open, its corresponding elements are displayed hierarchically in the Structure window, as shown in Figure 8-8.
Figure 8-8 Structure Window for Java File
If the Properties window is open, selecting elements in either the Structure window or the Java Visual Editor changes the selection in the Properties window as well.
Right-click anywhere within the Java Visual Editor to bring up a context-sensitive menu of commands. The context menus differ, depending upon whether you are editing non-menu or menu items, and the commands available within the context menu depend on the selected object.
To open the Java Visual Editor:
Double-click the Java file in the Applications window and click the Design tab in the editor window.
The source code is accessible in the Source Editor (click the Source tab to view the source code), enabling you to view and edit your source code in parallel with designing your UI. Any changes made in the Java Visual Editor or Properties window are immediately reflected in the source code.
The Java Visual Editor toolbar lets you easily work with components and duplicates commands that you can choose from the context sensitive menu displayed on a selected component.
For information on working with the Java Visual Editor, see Implementing Java Swing User Interfaces .
JDeveloper provides write protection for code that you are changing. It does this to preserve the code it requires to function. Figure 8-9 shows a section of Swing/AWT code that is colored grey, indicating that this section of code is protected.
Figure 8-9 Protected Code
You can use JDeveloper's editing commands to create and maintain Javadoc comments, such as those in Figure 8-10. After you enter Javadoc comments, you can use the Find in Files dialog to search for them.
Figure 8-10 Javadoc Comments
To add documentation comments to a source file:
Place the cursor just above the declaration of the class, field, or method to be documented, type the start of a documentation comment (/**
), and press Enter. Or,
With the code element selected in the Structure window, choose Source from the main menu, then Add Javadoc Comments.
A template for the documentation comment is inserted into the file. Add information to the template to describe the element.
You can update documentation comments in the Java Source Editor. Tags are added to or removed from the documentation comment to reflect changes you have made to the element. Add descriptions for the new tags.
To update documentation comments in a source file:
Every project you create carries the JDeveloper project defaults or those you have supplied yourself for all the projects across workspaces. You can also replace these defaults on a project-by-project basis. Setting these properties is the same in either case: only the location, and application, of the information differs.
To set Javadoc properties for an individual project:
You can customize the use of documentation comment tags in the Java code editor. You can define custom tags, and choose which tags will be automatically included when a documentation comment is created. These choices apply to all projects.
When creating custom tags, you can associate the tag with code elements, define it as required or not, assign it a default value, and give it an order in the tag list.
To define a custom tag:
When working in the Java Source Editor, you can quickly access Javadoc-generated documentation for the following code elements: a class, interface, or an individual member, using the Quick Javadoc feature.
As shown in Figure 8-11, the Quick Javadoc feature looks up the selected entity on the source path and displays the Javadoc comment entered in a popup window.
Figure 8-11 Quick Javadoc Window
If no Javadoc comment exists for that element, an empty Javadoc comment is displayed.
The Quick Javadoc feature is available when the selected source code meets the following criteria. It is:
On this project's source path.
On the source path of a project that the current project depends on.
Available for a library assigned to this project
A part of the JDK in use.
To display Javadoc for a code element:
You can preview documentation comments in your source files, in the same way that you view Javadoc for a single source element.
To display documentation comments for a given class, member, or method call:
You can validate documentation comments in your source files. The audit reports formatting errors and missing or extraneous tags.
To check documentation comments in a source file:
You can generate API references and other documentation directly from the Applications window, based upon the properties set for the project in the Javadoc page of the Preferences dialog. The documentation will be generated by the javadoc utility from the code and documentation comments in your files.
To build Javadoc on a package, file, or project:
You can create a reference to a missing annotation element when displaying an audit hints for an unresolved Java annotation in the Java Source Code editor.
To create a reference to a missing annotation:
The Java Object Tree (JOT) structure window displays a hierarchical tree of a source element selected in the Java Source Editor. For example, your Java file might contain code similar to the following:
public class Class1 implements Serializable{ @SuppressWarnings("serial:-4347721670334465144") // test private static final long serialVersionUID = -4347721670334465104; public Class2() { super(); } /* Non-javadoc comment */ public void a(){} // @SuppressWarnings("serial:23") private class foo{} }
Based on this, the JOT structure window displays at the bottom of JDeveloper, as shown in Figure 8-12. The hierarchy contains all of the child and parent source elements in the code. This could be the class, code blocks, or other elements.
Figure 8-12 JOT Structure Window
If you select a SourceElement in the Java Source editor, the corresponding SourceElement, including corresponding text, is highlighted in the JOT Structure window.
The Java Object Tree Structure is a JDeveloper extension that you must install to access this feature. Go to Help > Check for Updates to install the extension.
Once installed, display the JOT Structure window by choosing Window > JOT Structure Pane.
In the Java structure window, you can display Java and non-Java comments and blank lines in your Java code. For example, if Show comments and blank lines is selected and you set your cursor on a blank line in your Java code, the blank line displays in the tree with corresponding text, for example, SourceLexicalBlankline (SRC_LEX_BLANKLINE)
.
To display comments and blank lines:
You can use the Refresh on cursor update checkbox to allow refresh of the hierarchical tree on or off.
For example, with the checkbox selected, you might place your cursor on some text in your Java source file. The SourceElement of that text and its parents in the JOT tree display. In order to freeze the state of the JOT Structure Window and develop some code that uses this particular SourceElement, turn off the Refresh on cursor update checkbox. Load the Java source file you want to change. While you work, you can refer to the frozen state of the JOT tree.
To set the refresh mode:
Refactoring is an editing technique that modifies code structure without altering program behavior. A refactoring operation is a sequence of simple edits that transform a program's code but, taken together, do not change its behavior. After each refactoring operation, the program will compile and run correctly. JDeveloper provides a collection of automated refactoring operations.
Use refactoring when you modify a program's source code to make it easier to maintain, extend, or reuse. Perform the modification as a series of refactoring steps. After each step you can rebuild and re-validate the program to ensure that no errors have been introduced.
Table 8-1 contains some examples of simple refactoring operations.
Table 8-1 Refactoring Operations
Operation | Description |
---|---|
Renaming a method |
This operation finds usages of the target method and then allows users to decide whether to replace each name occurrence. |
Duplicating a class |
The definition of the class is replicated, and all occurrences of the class name in the replicated definition are replaced by the new name. |
Introducing a parameter into a method |
The method definition is modified by the addition of a parameter, and each method call is modified to provide an argument of the appropriate type and value. |
Changing a schema's target namespace |
All the referring schemas are updated to have the new target namespace. |
JDeveloper also provides more sophisticated refactoring operations such as:
Extracting an interface from a class by deriving member declarations from selected class members.
Pulling members of a class up into a superclass or pushing members down into a subclass by moving member definitions from one class to another.
Extracting a class replaces a set of fields or methods with a new container object.
Introducing a field, variable, parameter, or constant by replacing a selected expression with a reference to a new element constructed from the expression.
Extracting a method by replacing highlighted consecutive statements with a call to a new method constructed from the statements.
Extracting a method object to create a new method out of an existing block of code (similar to Extract Method) but moving it into a newly created inner class, converting all the local variables to fields of the class.
Introducing a parameter object replaces a set of fields or methods with a new container object.
If the results of the refactoring operation are not as desired, you can undo the refactoring as you would any editing operation, by pressing Ctrl+Z.
If you rename or move a class using the in-place edit functionality on a diagram, the source code for the class will be re-factored automatically. Renaming or moving a Java package on a diagram will automatically refactor the contents of that package.
Deleting a field, method, or inner class on a diagram will automatically apply the Delete Safely refactoring pattern. For more information, see How to Delete a Code Element .
To apply a refactoring pattern to a Java class, interface, enum, or member on a diagram, select the class or member on the diagram and choose the refactoring pattern from the Refactoring menu. Where a refactoring pattern is applied in this way, the appropriate dialog is displayed, including the facility to preview the results of the refactoring. For more information, see Refactoring Classes and Interfaces.
The following refactoring patterns are available for the Java classes, interfaces, and enums on a Java class diagram:
Rename
Move (applies to both single and multiple selections on the diagram)
Duplicate
Extract Interface
Extract Superclass
The following refactoring patterns are available for the Java fields and methods on a Java class diagram:
Rename
Move
Make Static
Pull Members Up
Push Members Down
Change Method (Java methods only)
JDeveloper provides a wide range of automated refactoring operations that enable you to enhance code quality. The external behavior of the code is not altered, yet its internal structure improves.
To invoke a refactoring operation:
You can also choose Refactor from the toolbar and select a refactoring operation from the drop-down list.
As shown in Figure 8-13, refactoring context menus contain different items depending on where in JDeveloper you are right-clicking to display the menu.
Figure 8-13 Refactoring Drop-down List
For example, you can display different context menus containing different refactoring operations by right-clicking on:
The structure menu
The beginning of the line of a method
The method's return type in the IDE
The method's name in the IDE
A parameter in the method's parameter list in the IDE
If the results of the refactoring operation are not what you want, you can undo the refactoring as you would any editing operation, by pressing Ctrl+Z.
When performing a refactoring operation that may modify many usages, it is helpful to preview the usages to identify those that should be modified by hand or be excluded. Depending on the refactoring operation you choose, you can click the Preview button in the refactoring dialog to see a preview of the changes that will occur. When you click Preview, a log window is displayed below the source editor. You can see the usages listed in the Preview Log window, from which you can inspect and resolve them, and if you wish, commit the operation.
The log displays a collapsible tree of packages and Java files. Under each file, lines of code containing usages are listed.
To view a usage in an Edit window, double-click the entry in the log.
To exclude a usage from the refactoring operation, right click it and choose Exclude.
To commit the refactoring operation:
While developing your Java application you can easily rename the definition and all references to a package, class, interface, method, field, parameter, or variable. If you wish, you can first generate a preview — a list of the usages that will be replaced. Use the Show Usages button to see the usages in a tree format.
The scope of a renaming operation is the full scope of the element in the project. Project, class, interface, and member usages are replaced anywhere they appear in the project. Parameters and variables are renamed only in the lexical scope of their definitions: other elements with the same name are not modified.
By default, the operation will be restricted to.java
files, excluding comments (but not documentation comment tags that name code elements) and annotations. Usages that are not ambiguous will be replaced. Usages of class and interface names will be replaced if they are fully qualified or if they are named in import statements.
For package, type, and member elements, you can choose to extend the operation to comments or to other files. When extended to comments, replacements will be made in line comments, commented-out code, the bodies of documentation comments, and in annotations. When the operation is extended to other files, text replacements will also be made in project files of types designated as text files in the File Types page of the Preferences dialog. Replacements in comments and other files will be made more aggressively than replacements in Java code.
To rename a code element:
While developing your Java application you can safely delete the definition of a class, interface, method, or field. The deletion will not be performed without your confirmation if the element is still in use.
If the element is in use a log showing the usages will be displayed. Use the list to inspect and resolve the usages. If you then confirm the deletion, any remaining usages will remain in the code as undefined references.
To delete a code element:
While developing your Java application you can easily define new classes and interfaces and re-purpose existing ones. For example, you can move a package, class, or interface to a different package. You can optionally generate a preview first, which is a list of the usages that will be replaced. Use the preview to inspect and modify or exclude selected usages, before completing the move.
When moving types, only primary classes and interfaces — those having the same name as their file — can be selected to be moved. In effect the file is renamed, and the definitions of secondary classes and interfaces remain with the primary. Accessibility will be preserved: if other classes in the original package refer to the class being moved, it will be given public access. If the class being moved refers to other classes in the original package, those classes will be made public.
The scope of an operation to move a class or interface is the entire project.
By default, the operation will be restricted to .java
files, excluding comments (but not documentation comment tags that name code elements) and annotations. Usages that are not ambiguous will be replaced. Usages will be replaced if they are fully qualified or if they are named in import statements.
You can choose to extend the operation to comments or to other files. When extended to comments, text replacements will be made in line comments, commented-out code, the bodies of documentation comments, and in annotations. When the operation is extended to other files, replacements will also be made in project files of types designated as text files in the File Types page of the Preferences dialog. Replacements in comments and other files will be made more aggressively than replacements in Java code.
To move a class or interface:
Classes can also be moved in the Applications window by dragging multiple classes from one package to another.
While developing your Java application you can easily duplicate a class or interface.
Only primary classes and interfaces, those having the same name as their file, can be selected to be duplicated. The duplicated class or interface is added to the same package as the original.
Member names in the new class are given the same name as those in the original, except for those derived from the original class or interface name. When the original name is embedded in a member name, the new name is substituted.
To duplicate a class or interface:
While developing your Java application you can easily derive a new interface from selected methods and static fields defined in an existing class.
Optionally, you can also generalize declarations, such as the type specifications of parameters, variables, and members, by replacing each type name in the declaration with the new interface name. Not all such declarations can be replaced. For example, the replacement cannot be done for the declaration of a variable that is used in a method invocation, if that method was not extracted into the new interface. The replacements will be done anywhere in the project.
The declaration of the class will be modified to show that it is an implementation of the new interface.
To extract an interface:
Extracting a superclasses allows you to add additional levels to a hierarchy even after the code is written.You can create a superclass based on chosen members of a selected class. The superclass consists of field and method declarations that match the chosen members.
To extract a superclass:
While developing your Java application you can easily generalize declarations — such as the type specifications of parameters, variables, and members — by replacing references to the selected class with references to one of its supertypes. Not all such declarations can be replaced. For example, the replacement cannot be done for the declaration of a variable that is used in a method invocation, if that method is not also defined in the supertype. The replacements will be done anywhere in the project.
To generalize declarations:
You can declare an inner class within the body of a method. You can also declare an inner class within the body of a method without naming it. This is known as an anonymous inner class. JDeveloper allows you to convert an unnamed inner class (an anonymous class) into a named inner class.
To convert an anonymous class into an inner class:
You can move an inner class to a newly created class at the top level. You might do this because the class is in the wrong package and you want to move it to another package where it fits better.
To move an inner class:
While developing your Java application, you can easily move member definitions from one class to another. For example, you can move a class member (for example, a method) to another class.
Methods declared with the static
keyword as a modifier are called static methods or class methods.
A static method does not use instance variables of any object of the class in which they are defined. The method signature for a main
method is static, which means that you don't need to create an instance of the class to invoke the main
method. If you define a method to be static, the compiler displays an error message if you try to access any instance variables.
To move a static method:
A non-static method can't be referenced from a static context. The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. A non-static method requires access to instance-level data in the class, for example, a non-static field.
To move a non-static method:
You can assign the static
modifier to a method. You can also specify what action to take when usages in a non-static context are found while making an element static.
To change a method to a static method:
You can change the signature of a method. The signature of a method is the combination of the method's name along with the number and types of the parameters (and their order.)
To change the signature of a method:
Note:
This feature does not apply to constructors.
While developing your Java application you can easily move the definitions of members from a class (the source class) to one of its superclasses (the target class). This operation can be applied to a class only if it has one or more potential target classes in the project. Members cannot be pulled up into library classes. Also, this refactor command is only available for a class that is declared with a superclass clause or a list of implemented interfaces.
By default, when a method is pulled up, its definition is moved from the source class to the target class. You can instead choose to abstract the method, in which case the method definition will remain in the source class, and a declaration for it will be added to the target class. Abstracting a method will convert the target class to an abstract class, if it is not already.
A member that you wish to pull up may have dependencies. A member is a dependency if it is used in the definition of a member that is to be pulled up. Pulling a member up without also pulling its dependencies up will introduce undefined references in the target class. When you select a member to be pulled up, its dependencies will be indicated. You can choose whether or not to pull up the dependencies as well.
When a member declared to be private is pulled up, its access changes to protected.
To pull members up:
While developing your Java application you can easily move the definitions of members from a class (the source class) to its immediate subclasses (the target classes).
By default, when a method is pushed down, its definition is moved from the source class to the target classes. You can instead choose to leave a method declaration in the source class, converting it to an abstract class, if it is not already.
A member that you wish to push down may have dependencies. A member is a dependency if its definition uses a member that is to be pushed down. Pushing a member down without also pushing its dependencies down will introduce undefined references in the source class. When you select a member to be pushed down, its dependencies will be indicated. You can choose whether or not to push down the dependencies as well.
To push members down:
While developing your Java application, you can easily convert expressions into named elements. For example, you can convert an expression into a reference to a field. A new field declaration will be added to the class, and the selected expression will become its initialization. The original expression will be replaced by a reference to the new field.
An expression cannot be converted into a field if its type is void
.
To introduce a field:
You can incorporate the body of a method into the body of its callers and remove the original method. This is known as inlining a method call.
To inline a method call:
While developing your Java application you can easily convert an expression into a reference to a variable. A new variable declaration will be added to the method, and the selected expression will become its initialization. The original expression will be replaced by a reference to the new member.
An expression cannot be converted into a member if its type is void
.
To introduce a member:
While developing your Java application, you can easily convert a constant expression in a method body into a new parameter for the method. The expression will be replaced by the new parameter name, the new parameter will be added to the method's parameter list, and in all invocations of the method the expression will be inserted as an additional argument.
Expressions can be introduced as parameters only if they are literals or operations on literals.
This operation is disallowed for methods that implement an interface. Altering the signature of such a method would invalidate the implementation.
To introduce a parameter:
While developing your Java application, you can easily convert a constant expression into a constant reference. The new constant declaration initialized by the expression will be added to the class, and the original expression will be replaced by the name of the constant.
Expressions can be introduced as constants only if they are literals or operations on literals.
To introduce a constant:
While developing your Java application you can easily extract part of the body of one method to create another. The extracted code is replaced in the original method with a call to the new method. Local variables and parameters used in the extracted code become parameters of the new method. An assignment made by a statement in the extracted code, if any, will be converted in the original member to an assignment that takes the value of the call to the new method.
To be extractable, a piece of code must satisfy several restrictions:
It must consist of a single complete expression, or a sequence of complete statements.
It cannot make an assignment to more than one variable whose declaration is external to the selection.
It cannot have more than one exit point. An exit point is a statement that throws an exception that is not caught in the selection, a break
or continue
statement for a loop outside of the selection, or a return
statement.
The new method is added to the same class as the original. The new method is declared to be private
.
Note:
Only the selected code block gets replaced by the extracted method. Other occurrences of the same code block do not get replaced.
To extract a method:
You can replace the fields and methods of a class by extracting a new class. All references to the fields are updated to access the new class. Extracting a class enables you to manage classes that have become too complex.
To extract a class:
You can convert a constructor into a factory method. Constructors create an instance of a class. Factory methods are static methods that return an instance of the native class. You can use factory methods for situations in which constructors are too limited.
To convert a constructor into a factory method:
Encapsulation makes the fields in a class private and provides access to the fields via public methods. If a field is declared private, it cannot be accessed by anything outline the class. This hides the fields within the class.You can change the fields of a class from being publicly accessible to being accessible only from within the class.
To encapsulate a field:
While developing your Java application, you can select a boolean field, parameter or local variable and initialize it with the opposite value. JDeveloper automatically corrects all references to maintain the same code functionality. JDeveloper looks at all fields, parameters and local variables and inverts all usages. This refactoring changes the sense of a Boolean method or variable to the opposite one. A Boolean expression evaluating to true
will be false
. Likewise, a Boolean expression evaluating to false
will be true
.
For example, if you have a variable that is enabled and you want to change to change the meaning to disabled, the Invert Boolean menu choice changes usages to disabled.
To invert a boolean method:
Table 8-2 Invert Boolean Example
Before | After |
---|---|
private double a;...public boolean method() { if (enabled){ a =5; return true; } false;} |
private double a;...public boolean method() { if (disabled{ a =5; return false; } return true;} |