11 Working with Java Code

This chapter describes how to take advantage of the JDeveloper tools and features that help you create the code for your Java applications. For example, you can browse Java elements in your application using a JDeveloper dialog or directly from an open file in the Java Source Editor. To edit Java code directly, you can use the Source Editor. Use the Visual Editor to display a diagram representing your Java code. For example, a Frame component displays as rectangular box, a button displays as a smaller button on top of the Frame, and so on.

Refactoring is useful when you want to modify a program's source code to make it easier to maintain, extend, or reuse. Refactoring is an editing technique that modifies code structure without altering program behavior.

This chapter includes the following sections:

11.1 About Working with Java Code

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 Section 3.8.1, "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 Section 3.8.2, "How to Set Preferences for the Source Editor."

11.2 Navigating in Java Code

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.

11.2.1 How to Browse Classes or Interfaces

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.

11.2.1.1 Browsing a Java Element Directly in JDeveloper

You can browse Java elements in the JDeveloper dialog shown in Figure 11-1,

To browse a Java element in JDeveloper: 

Figure 11-1 Go to Java Type Dialog

Go to Java Type Dialog
  1. From the main menu, choose Navigate > Go to Java Type.

    You can also use the keyboard shortcut, Ctrl-minus.

  2. In the Go to Java Type dialog, enter the name of the Java class or interface that you want to locate.

    When you begin entering text in this field, a list of Java entities matching the text displays. For example, entering j might display a list of classes that includes java.lang.

    You can drill down in the results returned in the Go to Java Type dialog. For example, double click on the java.lang class to display methods such as java.lang.Byte.

  3. Double-click an entity in the list to open it in the source editor.

11.2.1.2 Browsing a Class or an Interface in a Source File

You can browse a Java class or interface by selecting it in the Source editor.

To browse a class or an interface for a file currently open in the editor: 

  1. With the file open in the editor, ensure that the editor has focus.

  2. Select the class or interface name in the source file, right-click, and choose Go to 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.

    Figure 11-2 Highlighted Declaration

    Hightlighted Declaration

11.2.2 How to Locate the Declaration of a Variable, Class, or Method

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.

11.2.3 How to Find the Usages of a Class or Interface

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:

  1. Select the class or interface in one of the following ways:

    • In a Java Source Editor, select the name.

    • In a Applications window or the Structure window, select the class or interface.

  2. Invoke the command using one of the following ways:

    • Choose Search > Find Usages.

    • Right-click and choose Find Usages.

    • Press Ctrl+Alt-U.

      The Usages of <Object> dialog displays.

  3. In the Find box, select the types of references that the search will return.

  4. In the Where box, define the optional additional areas you want to search in.

  5. To direct the output of the search, select New Tab to direct the output to a new Usages Log.

    If not selected, the result of the previous search for usages, if any, are discarded.

  6. Click OK.

    The results display in the Usages Log window.

11.2.4 How to Find the Usages of a Method

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:

  1. Select the method in one of the following ways:

    • In a Java Source Editor, select the name.

    • In the Structure pane, select the method.

  2. Invoke the command in one of the following ways:

    • Choose Search > Find Usages.

    • Right-click and choose Find Usages.

    • Press Ctrl+Alt-U.

      The Usages of <Method> dialog displays. This dialog provides various options that you can specify to search for usages.

    • Specify options in the dialog and click OK to begin the search.

11.2.5 How to Find the Usages of a Field

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:

  1. Select the field in one of the following ways:

    • In a Java Source Editor, select the name.

    • In the Structure pane, select the field.

  2. Invoke the command in one of the following ways:

    • Choose Search > Find Usages.

    • Right-click and choose Find Usages.

    • Press Ctrl+Alt-U.

  3. Complete the Usages of <Object> dialog and click OK. You can specify options to extend the search to other areas, define the scope of the search, and optionally specify that the results be displayed in a new tab in the Log window.

    The search will commence, and the results will be displayed in the Usages of <Object> Log window.

11.2.6 How to Find the Usages of a Local Variable or Parameter

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:

  1. Select the variable or parameter name in the Java Source Editor.

  2. Invoke the command in one of the following ways:

    • Choose Search > Find Usages.

    • Right-click and choose Find Usages.

    • Press Ctrl+Alt-U.

      The results are displayed in the Usages Log window.

11.2.7 Identifying Overridden or Implemented Method Definitions

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 11-3.

Figure 11-3 Overrides Icon

Overrides icon

Overriden definitions are marked with the Implements margin icon in the Java Source Editor margin, as shown in Figure 11-4.

Figure 11-4 Implements Icon

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.

11.2.8 How to View the Hierarchy of a Class or Interface

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.

11.2.8.1 Opening a Hierarchy Initially in the Java Visual Editor

You can view the entire GUI hierarchy for a node in the editor. The entire GUI hierarchy for the node displays in the editor. The method of display depends upon whether this hierarchy consists of menu or non-menu items.

To open a hierarchy initially in the Java Visual Editor: 

  1. Select a node in the Applications window.

  2. Right-click and choose Edit, or use the View menu.

11.2.8.2 Viewing the Hierarchy of a Class or Interface in the Java Source Editor

The hierarchy window displays the hierarchy of the selected classes or interface.

To view the hierarchy of a class or interface in the Java Source Editor: 

  1. Select the class or interface, then either right-click and choose Types or choose Navigate > Types.

    The Hierarchy window will open (if it is not already open) and the tree of either subtypes or supertypes will be shown.

  2. To toggle the display between subtypes and supertypes, click the Subtype Hierarchy or Supertype Hierarchy button.

11.2.9 Stepping Through the Members of a Class

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.

These additional code-stepping commands are also defined, but are not assigned default accelerators:

  • Go to Next Class

  • Go to Next Field

  • Go to Next Method

  • Go to Previous Class

  • Go to Previous Field

  • Go to Previous Method

These commands are listed in the Navigate category of the Shortcut Keys page of the Preferences dialog. You can add or change accelerators. For more information, see Section 3.5.1, "How to Work with Shortcut Keys in the IDE."

11.3 Editing Java Code

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.

11.3.1 Editing Code with the Java Visual Editor

The Java Visual Editor displays the visual components of a user interface in Editing mode, as shown in Figure 11-5.

For example, the editor contains features that allow you to browse and locate your project's classes and interfaces and their members. You can find the usages of a class or interface, method, field, local variable or parameter.

Figure 11-5 Java Visual Editor

Java Visual Editor

When a Java Visual Editor is open, its corresponding elements are displayed hierarchically in the Structure window, as shown in Figure 11-6.

Figure 11-6 Structure Window for Java File

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 Inspector as well.

The Java Visual Editor displays a GUI hierarchy. If these are menu items, the hierarchy is displayed in one fashion. If these are non-menu items, it is displayed in another. The mode of presentation differs, as the sort of editing that you are engaged in differs.

To open a hierarchy initially in the Java Visual Editor, select a node in the Applications window and then right-click and choose Edit, or use the View menu. The entire GUI hierarchy for the this node displays in the editor. The method of display depends upon whether this hierarchy consists of menu or non-menu items.

When the node is selected in the Applications window, its GUI structure also displays in the Structure window. All non-menu GUI items for this object appear under a node labeled UI. Any menu items appear under a node labeled Menu. Any non-GUI items appear under a node labeled Other. Once you have opened the Java Visual Editor for an object in the Applications window, to switch between the display of non-menu GUI elements and menu elements you have only to click on a node below these UI or Menu nodes in the Structure window.

Because the display in the Java Visual Editor is rooted in the GUI hierarchy, when you click on a node (for all GUI objects) in the Structure window what loads into the editor is the visual representation of the root node and all its descendants: the entire hierarchy opens, regardless of which node in the hierarchy you selected. What displays in the editor reflects the complete GUI hierarchy; the specific element selected in the display reflects the specific node selected in the window. Selections in the Structure window and the Java Visual Editor are synchronized.

If you have an orphan node in the Structure window, that node and its descendants comprise the entire hierarchy, with the orphan being the root of the hierarchy. The Java UI display will reflect this. If you had a control, for instance, that was not parented, and you selected the node for that control, the control and any descendants would now appear in the editor, without a container. Any changes you make to that control, however, will result in generated code.

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.

11.3.2 Opening the Java Visual Editor

Right-click the Java file in the Applications window that you want to modify, choose Open and click the Design tab.

The source code is accessible in the Code Editor (right-click the file in the Applications window and choose Open to view the source code) so you can 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, and vice-versa.

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. Among the component operations included are:

  • Constraints to specify component weight, fill, anchor position, padding, and inset.

  • Alignment to quickly position components relative to one another.

  • Z-Order to change the sequence of stacked components.

11.3.3 What You May Need to Know About Java Visual Editor Proxy Classes

JDeveloper is a lightweight (JFC) application. Heavyweight components always obscure lightweight components, including the lightweight JDeveloper environment (including the Code Editor and UML Modelers).

The Java Visual Editor includes a proxy mechanism for registering lightweight proxies to represent heavyweight controls for instantiation in the Java Visual Editor. By default JDeveloper includes lightweight proxies for all the standard AWT controls.

11.3.4 How to Register a Java Visual Editor Proxy for Custom Components

Using heavyweight (AWT) controls directly in the Java Visual Editor will not work as expected. However, JDeveloper supports lightweight views of heavyweight components that you register for use by the Java Visual Editor.

To register the proxy class:

  • Add a key-value definition to oracle.jdevimpl.uieditor.UIEditorAddin section in the JDeveloper\lib\addins.xml file, as shown in Example 11-1.

Example 11-1 Key-value Definition

<property>
   <key>PREFIX.CLASS_NAME</key> 
   <value>PROXY_CLASS_NAME</value> 
</property> 

where:

  • PREFIX is jdeveloper.concreteProxy

  • CLASS_NAME is the fully-qualified classname of the heavyweight component for which a proxy is being registered

  • PROXY_CLASS_NAME is the fully-qualified classname of the proxy class to register

For example; if you were to register a heavyweight component implementation jdeveloper.concreteProxy.java.awt.Component using the oracle.jdevimpl.uieditor.proxy.Component proxy class, the property to add would look like Example 11-2.

Example 11-2 Heavyweight Component

<property>
   <key>jdeveloper.concreteProxy.java.awt.Component</key>
   <value>oracle.jdevimpl.uieditor.proxy.Component</value> 
</property> 

In order for the Java Visual Editor proxy class to be available from within the IDE, so that it will appear can be added to the Components window, the proxy class must be added to the IDEClasspath as a directive in JDeveloper\bin\jdev.conf file. For example:

AddJavaLibFile <myUiProxies.jar>

where myUiProxies.jar contains the compiled class file for your Java Visual Editor proxy implementation.

11.3.5 Protecting Code

JDeveloper provides write protection for code that you are changing. It does this to preserve the code it requires to function. Figure 11-7 shows a section of Swing/AWT code that is colored grey, indicating that this section of code is protected.

Figure 11-7 Protected Code

Protected Code

11.3.6 How to Create a New Java Class or Interface

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 access in the Applications window.

To create a new class and add it to a project:

  1. In the Applications window, select the project where you want to add the Java class, for example, client.

  2. Right-click and choose New > Java Class.

  3. In the Create Java Class dialog, enter the class or interface name, the package name, and the superclass that the new class will extend.

  4. Select attributes as needed.

  5. Click OK.

11.3.7 How to Implement a Java Interface

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:

  1. Open a Java source file.

  2. From the main menu, choose Source > Implement Interface.

  3. On the Search or Hierarchy tab, locate the class that will implement the interface and select the names of the interfaces that are to be implemented.

  4. If you want documentation comments from the overridden methods to be included, select Copy Javadoc.

  5. Click OK.

11.3.8 How to Override Methods

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:

  1. Open a Java source file.

  2. From the main menu, choose Source > Override Methods.

  3. In the Methods list, select the methods that are to be overridden.

    The list displays methods inherited from all superclasses. Abstract methods are shown in bold type. These must be implemented by non-abstract types.

  4. If you want documentation comments from the overridden methods to be included, select Copy Javadoc.

  5. Click OK.

    The stub method definitions are added to the class.

  6. Edit the stub definitions.

11.3.9 How to Use Code Templates

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.

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 Section 3.8.3, "How to Customize Code Templates for the Source Editor."

To evoke a defined code template:

  1. In the file open in the editor, put the cursor at the point where the template is to be inserted.

  2. Enter the shortcut associated with the template and then press Ctrl+Enter.

    The code as defined in the template is inserted in the source file. Import statements needed for the template, if any, are inserted at the top of the file.

Note:

Ctrl+Enter is the accelerator assigned in the default keymap. You can assign an alternative.

11.3.10 Using Predefined Code Templates

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

bc4jclient

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$) 
{

}

11.3.11 How to Expand or Narrow Selected Text

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:

  1. With the file open in the editor, ensure that the editor has focus.

  2. Put the cursor at the point where you want to expand the selection, or select a portion of the code.

  3. From the main menu, choose Source > Expand Selection, or press Ctrl+Shift+Equals.

    The selection expands to include the smallest logical unit containing the element previously selected or within which the cursor previously resided.

Use the Narrow Selection option (or press Ctrl+Shift+Minus) to successively reduce selected code in the same fashion.

11.3.12 How to Surround Code with Coding Constructs

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:

  1. With the file open in the editor, right-click within a statement, or select a block of code, and choose Surround. This options is available by right-clicking in the Visual Editor and choosing Surround from the context menu. Alternatively, you can click the Surround ({}) icon on the Source Editor toolbar.

    Note:

    This icon is only enabled when the selected code is a valid code block to which the Surround With feature can be applied.

  2. In the Surround With dialog, select the coding construct.

11.3.13 How to Fold Code

You can use code folding to hide and display sections of a file currently open in the Java Source Editor. If you have code inside a method such as that in Example 11-3, you can collapse the middle chunk of code so you don't have to see it when working on another part of the method.

Example 11-3 Code Folding Example

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.

11.3.14 Adding an Import Statement

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. JDeveloper will automatically add an import if it can find only one exact match for an unresolved reference to a class.

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 doesn't recognize a class, a lightbulb 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.

11.3.15 How to Organize Import Statements

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.

11.3.16 Using ojformat

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

11.4 How to Add Documentation Comments

You can use JDeveloper's editing commands to create and maintain Javadoc comments, such as those in Figure 11-8. After you enter Javadoc comments, you can use the <<???>> dialog to search for them.

Figure 11-8 Javadoc Comments

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.

11.4.1 How to Update Documentation Comments

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:

  1. In the Structure window, place the cursor on the element for which comments are to be updated.

  2. Right-click and choose Add Javadoc Comments.

11.4.2 How to Set Javadoc Properties for a Project

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:

  1. In the Applications window, select the project.

  2. From the main menu, choose Application > Project Properties, or right-click and choose Project Properties.

  3. Choose Javadoc.

  4. Set attributes.

  5. When finished, click OK to close the Project Properties dialog.

11.4.3 How to Customize Documentation Comment Tags

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:

  1. From the main menu, choose Tools > Preferences.

  2. In the Preferences dialog, choose the Code Editor > Java > Javadoc page.

  3. Click the Plus (+) icon.

    A tag with the default name new will be added to the list.

  4. In the Tag Properties box, change the name of the tag and set its other properties.

  5. When finished, click OK.

11.4.4 How to View Javadoc for a Code Element Using Quick Javadoc

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 11-9, the Quick Javadoc feature looks up the selected entity on the source path and displays the Javadoc comment entered in a popup window.

Figure 11-9 Quick Javadoc Window

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:

  1. Select the code element.

  2. From the main menu, choose Source > Quick Javadoc, or from within the editor, right-click and choose Quick Javadoc.

    A popup window displaying the documentation for the element appears. Click outside the window to close it.

11.4.5 How to Preview Documentation Comments

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:

  1. Select the name of the code element.

  2. Right-click and choose Quick Javadoc.

    A popup window showing the Javadoc for just that element now appears. From this window, you can link to other Javadoc as you would in a browser.

11.4.6 How to Audit Documentation Comments

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:

  1. In the Applications window, select the file to be checked.

  2. From the main menu, choose Build > Audit <filename>.

  3. In the Audit dialog, select Javadoc Rules from the Profile dropdown list.

  4. If you want to configure the audit to choose which types of errors to search for or to ignore, click Edit.

    The Audit Profile dialog opens.

  5. Click Run.

    The results of the audit appear in the Log window.

11.4.7 How to Build Javadoc

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:

  1. Select the appropriate node in the Applications window.

  2. From the main menu choose Build, then Javadoc.

    The Javadoc is generated in the background. Information and results appear in the Log window. A link in the Log window allows you to add the index.html file to the project.

11.4.8 How to Create References to Missing Annotation Elements

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:

  1. Open the Java class in the Java Source Code editor.

    For more information, see Section 3.8, "Working with Source Files."

  2. Enter the annotation in the Java class source code, for example, @stateless.

  3. Hover your cursor over the annotation.

    A dialog displays indicating that the type, for example, @stateless, cannot be found.

  4. Click the More link.

  5. Click the Create Annotation Type <type> link.

  6. In the Create Annotation Type dialog, enter the name of the package where you want to locate the annotation class, for example, project1.

  7. Click OK.

11.4.9 Using the JOT Structure Window

The JOT structure window displays a hierarchical tree of a SourceElement selected in the Java Source Editor. For example, your Java file might contain code similar to Example 11-4.

Example 11-4 Java Source Code

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 11-10. The hierarchy contains all of the child and parent SourceElements in the code. This could be the class, code blocks, or other elements.

Figure 11-10 JOT Structure Window

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.

To display the JOT Structure Window, in the Main menu, choose View > JOT Structure Window.

11.4.9.1 How to Display Comments and Blank Lines in the JOT Structure Window

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:

  1. In the Main menu, choose View > JOT Structure Window.

  2. Select Show comments and blank lines.

11.4.9.2 How to Set the Refresh Mode in the JOT Structure Window

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:

  1. In the Main menu, choose View > JOT Structure Window.

  2. Select Refresh on cursor updates.

11.5 Refactoring Java Projects

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 11-1 contains some examples of simple refactoring operations.

Table 11-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.

11.5.1 Refactoring on Java Class Diagrams

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 Section 11.5.5, "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 Section 11.5.6, "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)

11.5.2 How to Invoke a Refactoring Operation

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:

  1. Select a program element in a source editor window, Applications window, or structure pane.

  2. Right-click on the program element and choose Refactor.

  3. Choose an operation from the context menu, for example, Rename, Move, or Delete.

You can also choose Refactor from the toolbar and select a refactoring operation from the drop-down list.

As shown in Figure 11-11, refactoring context menus contain different items depending on where in JDeveloper you are right-clicking to display the menu.

Figure 11-11 Refactoring Drop-down List

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.

11.5.3 How to Preview a Refactoring Operation

When performing a refactoring operation that may modify many usages, it is useful to preview the usages to identify those that should be modified by hand or be excluded. You can preview using the Preview button. 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:

  1. If you have made any edits that affect usages, click the Refresh icon in the log toolbar to rerun the usages search.

  2. Click the Refactor button in the Preview log window.

11.5.4 How to Rename a Code Element

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:

  1. Select the element that is to be renamed in one of the two following ways:

    • In a Java source editor, select the element name.

    • In a window such as the Applications window or Structure window, select the element name.

  2. Invoke the command in one of the two following ways:

    • From the Main menu or the context menu, choose Refactor > Rename.

    • Press Ctrl+Alt-R.

      The Rename dialog opens.

  3. In the Rename To box, enter the new name. The name must be valid and not already in use.

  4. Set the depth of the text substitution.

    • Select Search Javadoc for Textual Usages to extend the operation to comments, the bodies of documentation comments, and to annotations.

    • (Package, type, and members elements only.) Select Search Text Files to extend the operation to other types of text files in the project.

  5. Select Preview if you wish to inspect the usages that will be replaced before committing to the renaming operation.

  6. Click OK.

    If you selected Preview, to avoid all the usages being modified, finish the renaming operation from the Preview log window.

11.5.5 How to Delete 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:

  1. Select the element that is to be deleted in one of the following ways:

    • In a Java source editor, select the name.

    • In a window such as the Applications window or Structure window, select the name.

  2. Invoke the command in one of the following ways:

    • From the Main menu or the context menu, choose Refactor > Delete.

    • Press Alt+Delete.

      The project files are searched for usages. The Confirm Delete dialog displays how many usages were found.

  3. Click the Show Usages button to inspect and resolve the usages in the log window.

  4. Select Preview to inspect the usages of the deleted file in the log window.

  5. Click OK.

11.5.6 Refactoring Classes and Interfaces

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:

  1. Select the package, class, or interface that is to be moved, in one of the following ways:

    • In a Java Source Editor, select the name.

    • In a Applications window or in the Structure window, select the name.

  2. Invoke the command in one of the following ways:

    • From the Main menu or the context menu, choose Refactor > Move.

    • Press Ctrl+Alt-M.

      The Move dialog opens.

  3. In the Move To field, enter the new package name.

    You can also click the Search icon next to the field to navigate to an existing package.

  4. Set the depth of the text substitution.

    • Update References In - In the drop-down list, choose where the references will be updated.

    • Search Javadoc for Textual Usages - Extend the operation to comments, the bodies of documentation comments, and to annotations.

    • Search Text Files - extend the operation to other types of text files in the project.

  5. Select Preview if you want to inspect the usages that will be replaced before committing to the move operation.

  6. Click OK.

    If you selected Preview, to avoid all the usages being modified, finish the renaming operation from the Preview log window. For more information, see Section 11.5.4, "How to Rename a Code Element."

Classes can also be moved in the Applications window by dragging multiple classes from one package to another.

11.5.7 How to Duplicate a Class or Interface

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:

  1. In a Java Source Editor, select the name of the class or interface that is to be duplicated.

    Note:

    Only primary classes and interfaces - those having the same name as their file - can be selected to be moved.

  2. From the Main menu, choose Refactor > Duplicate.

    The Duplicate type dialog opens.

  3. In the Class Name box, enter the new name.

    You can also specify a new package with the class, for example, client.frame1.

  4. Click OK.

    The new class will be added to the project.

11.5.8 How to Extract an Interface from a Class

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:

  1. Select the class from which the interface will be derived in one of the following ways:

    • In a Java Source Editor, select the class name.

    • In a Applications window or in the Structure Window, select the class name.

  2. From the Main menu, choose Refactor > Extract Interface.

    The Extract Interface dialog opens.

  3. In the Package field, enter the name of the package of the new interface.

  4. In the Interface field, enter the name of the new interface.

  5. In the Members to Extract table, select the members that will be included in the new interface.

  6. Select Replace Usages if you want to convert existing declarations that name the class into declarations naming the interface.

  7. Select Preview if you want to inspect the usages of the class before committing to the extract operation.

  8. Click OK.

11.5.9 How to Extract a Superclass

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:

  1. In a Applications window, in the Structure window, or in a Java Source Editor window, select the class name.

  2. From the main menu, choose Refactor > Extract Superclass.

    The Extract Superclass dialog opens

  3. In the Package field, enter the name of the package to which the new superclass will belong.

  4. In the Class Name field, enter a name for the new superclass.

  5. In the Members to Extract table, select the members that will be included in the new superclass.

    If you want a method to be created as an abstract method in the superclass, check the Abstract box against that method. If you want dependencies of a method to be included in the superclass, check the Dependencies box.

  6. Select Replace Usages if you want to convert existing declarations that name the class into declarations naming the superclass.

  7. Select Preview to view a list of the usages before committing to their replacement. This option is enabled only if you have selected Replace Usages.

  8. Click OK.

11.5.10 How to Use Supertypes Where Possible

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:

  1. Select the class or interface whose declarations will be generalized in one of the following ways:

    • In a Java Source Editor, select the name.

    • In a Applications window or in the Structure window, select the name.

  2. From the Main menu, choose Refactor > Use Supertype Where Possible.

    The Use Supertype dialog displays.

  3. In the Supertypes table, select the supertype that the declarations will be generalized to.

  4. Click OK.

11.5.11 How to Convert an Anonymous Class to an Inner Class

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 know 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:

  1. In a Java source editor window, select the declaration of the anonymous class.

  2. From the main menu, choose Refactor > Convert Anonymous to Inner Class.

    The Convert Anonymous to Inner Class dialog opens

  3. In the Class Name box, enter the name to be given to the inner class.

  4. If you want the inner class to be given the static modifier, check the Static box.

  5. To convert the anonymous class into an inner class, click OK.

11.5.12 How to Move 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:

  1. Select the inner class name in the Structure window or in a Java source editor window.

  2. On the main menu select Refactor > Move.

    The Move Inner Class dialog displays.

  3. If you do not want the new top level class to be created with the names already shown in the dialog, overwrite them or select new ones.

  4. To create a new class at the top level with the details shown in the dialog, click OK.

11.5.13 Refactoring Class Members

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.

11.5.13.1 Moving a Static Method

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: 

  1. Select the method name in the Structure window or in a Java Source Editor window.

  2. From the main menu select Refactor > Move.

    The Move Members dialog opens.

  3. In the Target panel, enter or choose the class to which the member will be moved.

  4. For each member that you want to move, ensure that the checkbox to its left in the Members to Extract list is checked.

  5. If you want the dependencies of a member to also be moved, check the corresponding checkbox in the Dependencies column.

11.5.13.2 Moving a Non-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: 

  1. Select the method name in the Structure window or in a Java Source Editor window.

  2. From the main menu select Refactor > Move.

    If there is at least one suitable target to which the member can move, the Move Member dialog opens. Otherwise, a message box is displayed.

  3. In the Targets panel, choose the class to which the member will be moved.

  4. If you want new names to be used for the method and the parameter in the new location, enter new names into the Method Name and Parameter Name boxes.

  5. Select how usages of the member will be handled after the move.

    • Select Use Delegate to handle usages through a newly created delegating method.

    • Select Replace to replace all usages with new ones that call the moved class member directly.

11.5.14 How to Change a Method to a 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:

  1. Select the method name in the Structure window or in a Java Source Editor.

  2. On the main menu select Refactor > Make Static.

    If the class is part of a class hierarchy, the Make Static dialog opens. Otherwise, the static modifier is added immediately.

  3. If the Make Static dialog opens:

    • In the Name box, enter or select a name to be used as a reference in the modified method.

      The options listed are derived from local object names.

    • If you want to create a method that cannot be overridden, check the Declare final box.

11.5.15 How to Change the Signature of a 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:

  1. Select the method name in the Structure window or in a Java Source Editor.

  2. On the main menu select Refactor > Change Method.

    The Change Method dialog opens.

  3. Make changes to the method name, return type, accessibility and parameters as required.

    If you change the name of the method to one that already exists in the class, you will later see a second dialog. Through this you can opt to replace all usages of the method that you are changing to usages of the existing method.

  4. If you want to create tasks based on the changes you have made and add them to the Tasks window, check the Add tasks to the task window box.

Note:

This feature does not apply to constructors.

11.5.16 How to Pull Members Up into a Superclass

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:

  1. Select the class from which the members will be pulled in one of the following ways:

    • In a Java Source Editor, select the name.

    • In a Applications window or the Structure window, select the name.

  2. From the main menu, choose Refactor > Pull Members Up.

    The Pull Members Up dialog will open.

  3. From the Target drop-down menu, choose the superclass that will be the target class.

  4. In the Members to Extract table, select the members you want to pull up.

    The members that are the dependencies of the selected members, if any, will be indicated.

  5. In the Abstract column, select the checkbox if you wish the method is to abstracted to the target class.

    Note:

    Members that are to be abstracted do not have dependencies.

  6. In the Dependencies column select the checkbox if you want to also pull up all of the member's dependencies.

    This selection is transitive. It will cause dependencies of dependencies to also be pulled up.

  7. Click OK.

11.5.17 How to Push Members Down into Subclasses

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:

  1. Select the class from which the members will be pulled in one of the following ways:

    • In a Java Source Editor, select the name.

    • In a Applications window or the Structure window, select the name.

  2. From the main menu, choose Refactor > Push Members Down.

    The Push Members Down dialog opens.

  3. In the Members to Extract table, select the members you want to push down.

    The members that are the dependencies of the selected members, if any, will be indicated.

  4. In the Abstract column, select the checkbox if you want an abstract definition of the member to be left in the source class.

  5. In the Dependencies column, select a checkbox to cause all the member's dependencies to be pushed down with the member.

  6. Click OK.

11.5.18 How to Introduce a Field

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:

  1. In the source editor, select the expression.

  2. From the main menu, choose Refactor > Introduce Field.

    The Introduce Field dialog opens.

  3. From the Type drop-down menu choose a type for the field.

    The menu lists all types that are consistent with the expression. This option will display if only a single type is valid.

  4. A suggested name displays in the Name text box.

    You can modify or replace it, or choose another suggestion from the drop-down menu.

  5. Select an initialization:

    • Select Current Method to put the assignment statement for the field immediately preceding the statement that contains the expression.

    • Select Field Declaration to assign the value to the field in its declaration statement. This option will not be enabled if the expression has a variable or parameter with local scope.

    • Select Constructor to assign the value to the field in the constructor methods of the class. This option will not be enabled if the expression has a variable or parameter with local scope.

  6. Click OK.

11.5.19 How to Inline a Method Call

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:

  1. In a Java Source Editor, select an instance of the method call that you want to be inlined.

  2. From the main menu select Refactor > Inline.

    • If there is only one call to the method in this class, the change is made immediately.

    • If there is more than one call to the method in this class, the Inline dialog opens.

  3. If the Inline dialog has opened:

    • Choose between inlining only the selected instance of the call or inlining all instances of the call.

    • Click OK.

11.5.20 How to Introduce a Variable

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:

  1. In the source editor, select the expression.

  2. From the main menu, choose Refactor > Introduce Variable.

    The Introduce Variable dialog opens.

  3. From the Type drop-down menu choose a type for the field.

    The menu lists all types that are consistent with the expression. This option will not be shown if only a single type is valid.

  4. A suggested name will be shown in the Name text box.

    You can modify or replace it, or choose another suggestion from the drop-down menu.

  5. Select Declare final if you want to add the final modifier to the variable's declaration.

  6. Click OK.

11.5.21 How to Introduce a Parameter

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:

  1. In the source editor, select the expression.

  2. From the main menu, choose Refactor > Introduce Parameter.

  3. From the Type drop-down menu, choose a type for the field.

    The menu lists all types that are consistent with the expression. This option is not displayed if only a single type is valid.

  4. A suggested name displays in the Name text box.

    You can modify or replace it, or choose another suggestion from the drop-down menu.

  5. Select Declare final if you want to add the final modifier to the variable's declaration.

  6. Click OK.

11.5.22 How to Introduce a Constant

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:

  1. In the source editor, select the expression.

  2. From the main menu, choose Refactor > Introduce Constant.

    The Introduce Constant dialog opens.

  3. From the Type drop-down menu choose a type for the field.

    The menu lists all types that are consistent with the expression. This option is not shown if only a single type is valid.

  4. A suggested name displays in the Name text box.

    You can modify or replace it, or choose another suggestion from the drop-down menu.

  5. Click OK.

11.5.23 How to Extract a Method

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:

  1. In the source editor, select the expression or the sequence of expressions that you wish to extract.

  2. From the main menu, choose Refactor > Extract Method.

  3. Enter a name for the new method.

  4. In the Parameters list, specify the substitutions that will be made for the local variables and parameters that appear in the selected code:

    • In the Name column replacement names, which are similar or identical to the original names, are proposed. You can select and modify the names.

    • In the Included column, select the proposed parameters that will become the parameters of the new method. Those that you deselect will become uninitialized local variables in the new method.

    • Use the Up and Down buttons to order the parameters

  5. Select static if you want to declare the new method to be static.

    This option is disabled if the method is forced to be static because it is called from a static method, or if it is forced to be non-static because it uses a non-static member.

  6. Click OK.

    The new method is added to the class, and the code you selected will be replaced by a call to the new method.

  7. If you deselected any of the proposed parameters in the Parameters list, edit the new method to initialize its local variables.

11.5.24 How to Replace a Constructor with a Factory Method

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:

  1. Select the constructor name in the Structure window or in a Java Source Editor.

  2. From the main menu, select Refactor > Replace Constructor With Factory Method.

  3. In the Method Name box, enter a name for the new method.

    A suggested name based on the current class name already appears in the box.

  4. To convert the constructor into a factory method click OK.

11.5.25 How to Encapsulate a Field

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:

  1. Select the field name (or its parent class) in the Structure window or in the Java Source Editor.

  2. On the main menu select Refactor > Encapsulate Fields.

  3. In the Fields table, check the box next to each field that you want to be encapsulated.

    For each field, you can, you can also specify options for method/field accessibilities and the scope for replacements.

  4. In the Replace Accessors box, select how you would like accessors to be replaced as part of the encapsulation.

  5. If you want to create tasks based on the changes you have made and add them to the Tasks window, check the Add tasks to the task window box.

  6. Click OK.

11.5.26 How to Invert a Boolean Expression

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:

  1. In the source editor, select the boolean expression.

  2. Right-click on the expression and choose Refactor > Invert Boolean.

    Table 11-2 contains an example of an inverted boolean expression.

Table 11-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;}


11.5.27 Refactoring XML Schemas

When a schema's target namespace changes, all the referring schemas are updated to have the new target namespace.

When you change the base type on a simpletype element that has facets, all facets are not removed. Instead, the facets that are still valid are retained.