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

About Working with Java Code

In the Java Source Editor, write or edit Java code with predefined code templates, add Javadoc comments, and apply formatting to code. Access the features from the context menu and the Source main menu.

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. See Using the Source Editor.

You can customize the behavior of the Java Source Editor by specifying preferences in the Preferences Dialog. See How to Set Preferences for the Source Editor.

Navigating in Java Code

JDeveloper provides Java-aware editing features such as moving to the source code of classes and interfaces and their members, and navigating with keyboard accelerators from member to member in a class definition in the Java 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.

How to Browse Java Elements

Browse Java elements either from a JDeveloper dialog or from a file that is open 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.

Browsing a Java Element Directly in JDeveloper

Use the Go to Java Type Dialog to browse Java elements. Use the procedure to browse a Java element in JDeveloper.

You can browse Java elements in the Jdeveloper dialog.

To browse a Java element in Jdeveloper:

  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.

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

In the Java Source Editor, locate the declaration of any identifier. Follow the steps to navigate to the declaration of a code element.

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-1 Highlighted Declaration

Description of Figure 8-1 follows
Description of "Figure 8-1 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.

How to Find the Usages of a Class or Interface

In the Java Source Editor, search for references to a class or interface and its members. Use the procedure to find the usages of a class.

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 the Java Source Editor, select the name.

    • In the Applications window or the Structure window, select a class or an 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.

How to Find the Usages of a Method

In the Java Source Editor, search for references to a method. Use the procedure to find usages of a method to instances of the class or interface for which the method is defined, or usages of its subclasses or subinterfaces that inherit the 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.

How to Find the Usages of a Field

In the Java Source Editor, search for references to a field in instances of the class or interface for which the field is defined, and instances of its subclasses or subinterfaces that inherit the field. Use the procedure 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.

How to Find the Usages of a Local Variable or Parameter

In the Java Source Editor, search for references to a local variable or a parameter in a method body. Use the procedure 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.

Identifying Overridden or Implemented Method Definitions

In the Java Source Editor, methods that override or implement superclass definitions can be identified. Click Overrides or Implements in the margin to view the overridden definition of a method.

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 Overrides.

Overridden definitions are marked with the Implements margin icon Implements, in the Java Source Editor margin.

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.

How to View the Hierarchy of a Class or Interface

In the Java Source Editor, inspect the hierarchy of subtypes and supertypes 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.

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

View the hierarchy of selected classes or interface in the hierarchy window. Use the procedure to view 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 Types window opens (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.

Stepping Through the Members of a Class

In a Java Source Editor, use keyboard accelerators to move from member to member in a class definition. Use the code-stepping commands listed in the Navigate category of the Shortcut Keys page of the Preferences dialog or the Navigate options to navigate between members.

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.

Editing Java Code

JDeveloper provides Java-aware editing tools such as the Java Visual Editor, Source Editor, and the Visual Editor.

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.

How to Create a New Java Class or Interface

Create an application, a project, a new class, or an interface that JDeveloper adds to an active project, and displays in the Java Source Editor. Use the procedure to create a new class, and add it to a project.

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:

  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.

How to Implement a Java Interface

In the source editor, add framework code that modifies a target class to implement an interface, or make a target interface extend another interface. Use the procedure to implement an 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.

How to Override Methods

In the source editor, add stub definitions to a class to override methods inherited from superclasses. Use the procedure 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.

How to Convert an Anonymous Inner Class to a Lambda Expression

Lambda expressions provide a mechanism to express instances of anonymous inner classes that contain only a single method. Use the procedures to convert an inner class to a lambda expression, and to turn off the feature.

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:

  1. In the Java source editor, select the anonymous class to convert.

    The IDE analyzes the code to check if code assist is applicable.

  2. Click the code assist icon that appears in the editor margin.

  3. Click the code assist Convert Anonymous Inner Class to a Lambda Expression.

    The lambda expression replaces the inner class.

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:

  1. Go to Tools > Preferences and click the Audit node.
  2. Click Edit Profiles on the Audit page.
  3. Click the Code Assists tab.
  4. Expand the following Code Assists category nodes: Java SE > Java > Code Assists.
  5. Uncheck the Eligible Lambda Expression to make the feature unavailable.

    Select to make the feature available through code assist.

How to Use Code Templates

Use the predefined code templates in JDeveloper to insert text for commonly used statements. Use the procedure to evoke a defined code template.

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. See 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.

Using Predefined Code Templates

Use the predefined JDeveloper code templates in the list to insert code for commonly used statements.

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

}

How to Expand or Narrow Selected Text

Use the Expand or Narrow Selection option to expand or narrow a selected block of code. Use the procedure to expand selected code.

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.

How to Surround Code with Coding Constructs

In the Java Source Editor, use coding constructs to surround Java statements and blocks. Use the procedure to surround a block of code with a construct.

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.

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. See How to Customize Code Templates for the Source Editor.

How to Fold Code

In a file open in the Java Source Editor, code folding collapses selected blocks of code so that other areas of code can be viewed better. Follow the steps to use code folding.

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.

Adding an Import Statement

Any unresolved reference to an unavailable class in the Source Editor causes JDeveloper to import the class, or display possible matches for selection so that an import statement can be added. Set Import Statement Options in the Java Source Editor to configure or disable Import assistance.

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-2 Import Statement Needed

Description of Figure 8-2 follows
Description of "Figure 8-2 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.

How to Organize Import Statements

Organize import statements in the Java Source Editor by setting the options for organizing imports in the Preferences dialog. Follow the step to organize import statements in a source file.

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.

Using ojformat

Use the ojformat command line tool that is located in <JDeveloper_Home>/jdev/bin to reformat workspaces or projects.

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

Editing with the Java Visual Editor

The Java Visual Editor displays the visual components of a user interface in Design so that you can view and edit source code as you design the UI. Use Source in Source Editor to access the source code.

The Java Visual Editor displays the visual components of a user interface in the Design tab, as shown in Figure 8-3.

Figure 8-3 Java Visual Editor Design View

Description of Figure 8-3 follows
Description of "Figure 8-3 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-4.

Figure 8-4 Java Visual Editor Source View

Description of Figure 8-4 follows
Description of "Figure 8-4 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-5.

Figure 8-5 Structure Window for Java File

Description of Figure 8-5 follows
Description of "Figure 8-5 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 .

Protecting Code

JDeveloper supports write protection for code that changes by preserving code that is required for its functioning.

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

How to Add Documentation Comments

Create and maintain Javadoc comments using the editing commands in JDeveloper. Follow the steps to add documentation comments to a source file.

You can use Jdeveloper's editing commands to create and maintain Javadoc comments, such as those in Figure 8-7. After you enter Javadoc comments, you can use the Find in Files dialog to search for them.

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.

How to Update Documentation Comments

In the Java Source Editor, record changes that are made to elements by adding or removing tags from documentation comments, and adding tag descriptions. Use the procedure to update documentation comments in a source file.

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.

How to Set Javadoc Properties for a Project

JDeveloper provides project defaults that you can modify for individual projects or for all projects across workspaces. Use the procedure to set Javadoc properties for an individual 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.

How to Customize Documentation Comment Tags

Customize usage of documentation comment tags in the Java code editor by creating custom tags, associating the tag with code elements, defining it for inclusion in a project, assigning it a default value, and giving it an order in the tag list. Use the procedure to define a custom tag.

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.

How to View Javadoc for a Code Element Using Quick Javadoc

In the Java Source Editor, when the selected source code satisfies certain criteria, the Quick Javadoc feature becomes available so that you can use Javadoc comments for classes, interfaces, or individual members. Use the procedure to display Javadoc for a code element.

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-8, 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-8 Quick Javadoc Window

Description of Figure 8-8 follows
Description of "Figure 8-8 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.

How to Preview Documentation Comments

The Quick Javadoc feature allows you to preview documentation comments in source files. Use the procedure to display documentation comments for a given class, member, or method call.

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.

How to Audit Documentation Comments

Use the Audit Profile and Audit filename options for Javadoc Comments to validate documentation comments in source files. Use the procedure to check documentation comments in a source file.

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 with the Rules tab selected.

  5. Expand JavaSE > Java > Javadoc Comments nodes and select one or more Javadoc rules. Select an item to see a description of the validation check. For each item, you can set the property values for each rule.
  6. Click OK in the Audit Profile dialog.
  7. Click Run in the Audit filename dialog.

    The results of the audit appear in the Log window.

How to Build Javadoc

Set properties for a project on the Javadoc page of the Preferences dialog to generate API references and other documentation from the Applications window. Use the procedure to build Javadoc on a package, file, or project.

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.

How to Create References to Missing Annotation Elements

When auditing unresolved Java annotations in the Java Source Code editor, create references to missing annotation elements. Use the procedure to create a reference to a missing annotation.

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

Using the JOT Structure Window

The Java Object Tree structure window displays the hierarchy of a source element that is selected in the Java Source Editor. Install the Java Object Tree Structure extension using Check for Updates in Help, and get the extension window displayed by selecting JOT Structure Pane from the Window options.

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-9. 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-9 JOT Structure Window

Description of Figure 8-9 follows
Description of "Figure 8-9 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.

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

The JOT Structure Window displays Java and non-Java comments and blank lines in Java code. Use the procedure to display comments and blank lines.

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.
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 Window > JOT Structure Window.
  2. Select Refresh on cursor updates.

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

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

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 8-10, refactoring context menus contain different items depending on where in Jdeveloper you are right-clicking to display the menu.

Figure 8-10 Refactoring Drop-down List

Description of Figure 8-10 follows
Description of "Figure 8-10 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.

How to Preview a Refactoring Operation

A preview provides a view of usages so that they can be inspected and resolved before they are committed. Use the procedure to commit a refactoring operation.

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:

  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.

How to Rename a Code Element

In the .java files of an application, unambiguous definitions and all references to code elements such as a package, class, interface, method, field, parameter, or variable can be renamed. Use the procedure 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.

How to Delete a Code Element

JDeveloper deletes the definition of a class, interface, method, or field after a deletion is confirmed, leaving undeleted code as undefined references. Use the procedure 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.

Refactoring Classes and Interfaces

In .java files, primary classes and interfaces can be repurposed, or new ones defined. Use the procedure to move a class or interface.

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 an 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 the bodies of documentation.

    • 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.

    You can also click Show Usages to open a display panel within the Move dialog to see a list of all current usages in the project.

  6. Click OK.

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

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

How to Duplicate a Class or Interface

JDeveloper duplicates selected primary classes and interfaces, and adds them to the same package as the original. Use the procedure 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.

How to Extract an Interface from a Class

When a new interface is derived from selected methods, and static fields are defined in a class, the modified declaration of the class displays it as an implementation of the new interface. Use the procedure to extract an 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:

  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 an 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.

How to Extract a Superclass

An extracted superclasse based on the selected members of a selected class adds additional levels to the hierarchy of written code. Use the procedure 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 an 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.

How to Use Supertypes Where Possible

Generalize type specifications of declarations in Java code into supertypes by replacing references to a selected class with references to one of its supertypes. Use the procedure to generalize declarations.

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 an 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.

How to Convert an Anonymous Class to an Inner Class

Unnamed inner classes or anonymous classes can declare and instantiate a class at the same time, and named inner classes can access everything in their enclosing class. Use the procedure to convert an anonymous class into 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 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:

  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.

How to Move an Inner Class

Converting an inner class to a top level class renders code less bulky and more readable. Use the procedure 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.

Refactoring Class Members

Refactoring that involves relocating member definitions from one class to another restructures the code to make it simple and readable.

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.

Moving a Static Method

Static methods belong to the class and does not use instance variables of any object of the class in which they are defined. Use the procedure to move 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.
Moving a Non-static Method

Non-static methods can only be called on an instance of the class itself, and they perform something that depends on the individual characteristic of the class. Use the procedure to move 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.

How to Change a Method to a Static Method

A static method, used for memory management, belongs to the class rather than the object of a class, and can be invoked without creating an instance of a class. Use the procedure 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.

How to Change the Signature of a Method

A method signature comprises the method name and the number and type of its parameters. Use the procedure 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.

How to Pull Members Up into a Superclass

Moving definitions of members from a source class to one of its superclasses retains the functionality of the class member while making code simple and readable. Use the procedure to pull a member 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 an 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 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.

How to Push Members Down into Subclasses

Moving the definitions of members from a class to its immediate subclasses cleans up the class hierarchy. Use the procedure to push a member down into a subrclass.

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 an 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.

How to Introduce a Field

Covert Java expressions into named elements. Use the procedure 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.

How to Inline a Method Call

Code compilation saves overheads by inlining or including the body of a method into the body of its callers. Use the procedure 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.

How to Introduce a Variable

In the source editor, add a new variable declaration to a method for a selected expression. Use the procedure to introduce a member.

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. If more than one data type is valid for the field, choose the Type from the drop-down list.

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

  4. Modify or replace the suggested name for the variable in the Name field.

    You can choose a suggested name 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.

How to Introduce a Parameter

In the source editor, convert a constant expression in a method body into a new parameter for the method. Use the procedure 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. Modify or replace the suggested name for the variable in the Name field.

    You can choose a suggested name 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.

How to Introduce a Constant

Convert a constant expression into a constant reference so that the constant declaration that is initialized by the expression is added to the class. Use the procedure 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. Modify or replace the suggested name for the variable in the Name field.

    You can choose a suggested name from the drop-down menu.

  5. Click OK.

How to Extract a Method

Create a new private method from the local variables and parameters of a method that conform to certain restrictions. Use the procedure 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.

How to Extract a Class

To simplify complex classes, extract a new class by replacing the fields and methods of a class. Use the procedure to extract a class.

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:

  1. In the source editor, select the class that you wish to extract.
  2. From the main menu, choose Refactor > Extract Class.
  3. Enter a name for the new class.
  4. Select Inner Class to make the new class is an inner class.

    If you do select this option, a top-level class is created.

  5. Select whether you want to generate getter and setter methods for the extracted fields in the new class.
  6. Select the methods to extract for the new class.
  7. Select Replace Usages to replace all usages of the extracted class.

How to Replace a Constructor with a Factory Method

Create a factory method and use it to replace the calls of a constructor to overcome its limitations. Use the procedure to convert a constructor into 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.

How to Encapsulate a Field

Encapsulation makes field data accessible only by public methods, thus hiding the private fields and their implementation for outside classes. Use the procedure 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.

How to Invert a Boolean Expression

JDeveloper updates all references to maintain code functionality if a boolean field, parameter or local variable is initialized after its value has been reversed. Use the procedure to invert a boolean method.

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 8-2 contains an example of an inverted boolean expression.

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

Refactoring XML Schemas

Referring schemas are updated to reflect all changes made to the namespace of a schema target.

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.