This chapter describes how to use the tools and features provided by JDeveloper to build Java applications. It explains how to define classes on a diagram. Class members, inheritance, and composition relationships are all derived directly from the Java source code for those classes.
This chapter includes the following sections:
JDeveloper enables you to build and assemble Java applets and client applications using JavaBeans, and interactive, desktop-based GUI applications using Swing and AWT components. You can also create and run Java client applications with Java Web Start within the JDeveloper IDE.
JDeveloper provides resources for performing the following tasks in the Java domain:
Modeling Java Classes - Tools to visually create Java classes and interfaces, or to graphically view existing Java classes and interfaces.
Editing Java Source Files - The Source Editor supports several Java-aware editing features.
Refactoring Java Projects - A collection of automated refactoring operations that modify code structure without altering program behavior.
Building Apache Ant - Compile projects using the Make and Rebuild commands, or Apache Ant.
Running Java Programs - Keep track of processes that are run, debugged, or profiled.
Debugging Java Programs - Tools for local and remote debugging.
Optimizing Application Performance - Tools for analyzing the quality and performance of your Java code.
Unit Testing with Junit - Tools to write and run tests that verify Java code, using the open source JUnit framework.
JDeveloper supports Java-aware features for locating and moving to the source code for your projects' classes and interfaces and their members.
While working in JDeveloper, you can browse Java elements directly from the UI or directly from a file open in the Java Source Editor.
To browse a Java element directly from the UI:
From the main menu, choose Navigate > Go to Java Type. Or, you can use the keyboard shortcut, Ctrl-minus.
In the Go to Java Type dialog, enter the name of the Java type that you want to locate. When you begin entering text in this field, a list of Java entities matching the text is displayed.
Double-click an entity in the list to open it in the source editor.
To browse a class or an interface for a file currently open in the editor:
With the file open in the editor, ensure that the editor has focus.
Select the class or interface name in the source file, right-click, and choose Go to Declaration.
The source file opens in the Java Source Editor.
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.
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 will be reported. You can extend the search to libraries if the source files for the libraries are accessible.
The Find Usages command can also be applied to individual methods and fields, and to local variables and parameters.
To find the usages of a class:
Select the class or interface in one of the following ways:
In a Java Source Editor, select the name.
In a navigator or the Structure window, select the class or interface.
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 will open
In the Find box select the types of references that the search will return.
In the Where box define the optional additional areas you want to search in.
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, will be discarded.
Click OK.
The search will commence, and the results will be displayed in the Usages Log window.
While working in the Java Source Editor, you can quickly locate references to a method.
The search will show applications of the method to instances of the class or interface for which the method is defined and also for instances of its subclasses or subinterfaces, if any, that inherit the method.
The Find Usages command can also be applied to classes and interfaces, fields, and to local variables and parameters.
To find the usages of a method:
Select the method in one of the following ways:
In a Java Source Editor, select the name.
In the Structure pane, select the field.
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.
While working in the Java Source Editor, you can quickly locate references to a field.
The search will show references to the field in instances of the class or interface for which the field is defined and also for instances of its subclasses or subinterfaces, if any, that inherit the field.
The Find Usages command can also be applied to classes and interfaces, methods, and to local variables and parameters.
To find the usages of a field:
Select the field in one of the following ways:
In a Java Source Editor, select the name.
In the Structure pane, select the field.
Invoke the command in one of the following ways:
Choose Search > Find Usages.
Right-click and choose Find Usages.
Press Ctrl+Alt-U.
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.
While working in the Java Source Editor, you can quickly locate references to a local variable or a parameter in a method body.
The Find Usages command can also be applied to classes and interfaces, methods, and fields.
To find the usages of a local variable or parameter:
Select the variable or parameter name in the Java Source Editor.
Invoke the command in one of the following ways:
Choose Search > Find Usages.
Right-click and choose Find Usages.
Press Ctrl+Alt-U.
The search will commence, and the results will be displayed in the Usages Log window.
While working in the Java Source Editor, you can easily identify methods that override superclass definitions. Overriding definitions are marked with the Overrides up arrow icon in the Java Source Editor margin.
To view the overridden definition of a method, click the Overrides margin icon.
If you navigate to the override, then click the Back Main toolbar button to return to the previous view.
While working in the Java Source Editor, you can easily identify methods that override superclass definitions. Overriding definitions are marked with the Implements down arrow icon in the Java Source Editor margin.
To view the overridden definition of a method, click the Implements margin icon.
If you navigate to the override, then click the Back Main toolbar button to return to the previous view.
While working in the Java Source Editor, you can inspect the hierarchy of subtypes and supertypes of a class or interface. 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:
Select the class or interface, then either right-click and choose Type Hierarchy or choose Navigate > Type Hierarchy.
The Hierarchy window will open (if it is not already open) and the tree of either subtypes or supertypes will be shown.
To toggle the display between subtypes and supertypes, click the Subtype Hierarchy or Supertype Hierarchy button.
To open a hierarchy initially in the Java Visual Editor:
Select a node in the Navigator.
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 nonmenu items.
You can use keyboard accelerators to step from member to member in a class definition in a Java Source Editor:
To step to the next member definition or declaration in the current Java source view, press Alt-Down, or choose Navigate > Go To Next Member.
To step to the previous member definition or declaration in the current Java source view, press Alt-Up, or choose Navigate, then Go To Previous Member.
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.
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.
The Java Visual Editor displays the visual components of a user interface in Editing mode.
When a Java Visual Editor is open, its corresponding elements are displayed hierarchically in the Structure window. If the Property Inspector 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 nonmenu 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, you have only to select a node in the Navigator 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 nonmenu items.
When the node is selected in the Navigator, its GUI structure also displays in the Structure window. All nonmenu 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 Navigator, to switch between the display of nonmenu 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 kept in synch.
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 nonmenu or menu items, and the commands available within the context menu depend on the selected object.
Right-click the Java file in the Navigator that you want to modify and choose Open > click the Design tab.
The source code is accessible in the Code Editor (right-click the file in the Navigator 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 Property Inspector 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.
JDeveloper is a lightweight (JFC) application. As such, using heavyweight (AWT) controls directly in the Java Visual Editor will not work as expected. 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.
JDeveloper supports lightweight views of heavyweight components that you register for use by the Java Visual Editor.
Add a key-value definition to oracle.jdevimpl.uieditor.UIEditorAddin
section in the JDeveloper\lib\addins.xml
file, as shown in Example 18-1.
Example 18-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 hypothetical 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 18-2.
Example 18-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 Component Palette, 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.
Before creating a new class, note that you must first create an application and a project. As soon as you create the class, it is added to the active project.
To create a new class and add it to a project:
In the Application Navigator, select the project you want to add the class to.
Right-click and choose New.
In the New Gallery, under the General category, select Java.
Under Items, select Class.
In the Create Java Class dialog, enter the class name, the package name, and the superclass that the new class will extend. Select attributes as needed.
Click OK.
The new class appears in the active project.
Before creating a new interface, note that you must first create an application and a project. As soon as you create the interface, it is added to the active project.
To create a new interface and add it to a project:
In the Application Navigator, select the project you want to add the class to.
Right-click and choose New.
In the New Gallery, under the General category, select Java.
Under Items, select Interface.
In the Create Java Interface dialog, enter the interface name, the package name, and the superclass that the new class will extend. Select attributes as needed.
Click OK.
The new class appears in the active project.
In the source editor, you can quickly add framework code to modify a target class to implement an interface or to make a target interface extend another interface.
An implements
or extends
clause is added to the declaration for the target class or interface, and an import statement is added to the file. If the target is a class, stub definitions for the implemented interface's methods are appended to the class or interface body.
Open a Java source file.
From the main menu, choose Source > Implement Interface.
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.
If you want documentation comments from the overridden methods to be included, select Copy Javadoc.
Click OK.
In the source editor, you can quickly add stub definitions to a class to override methods inherited from superclasses.
Open a Java source file.
From the main menu, choose Source > Override Methods.
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.
If you want documentation comments from the overridden methods to be included, select Copy Javadoc.
Click OK.
The stub method definitions are added to the class.
Edit the stub definitions.
JDeveloper provides predefined code templates that you can use. Code templates 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 (int i = 0; i < unknown.size(); i++) { Object object = (Object) unknown.get(i); }
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.
To evoke a defined code template:
In the file open in the editor, put the cursor at the point where the template is to be inserted.
Type 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.
This section lists the predefined code templates. The shortcut and the code that the template introduces are shown for each.
ai for (int $i$ = 0; $i$ < $array$.length; $i$++) { $type$ $var$ = $array$[$i$]; $end$ }
daev public void on$end$(PageLifecycleContext ctx) { }
for for ($end$ ; ; ) { }
if if ($end$) { }
ife if ($end$) { } else { }
fori for (int $i$ = 0; $i$ < $lim$; $i$++) { $end$ }
forn int $n$ = $lim$; for (int $i$ = 0; $i$ < $n$; $i$++) { $end$ }
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);
itar for (int $i$ = 0; $i$ < $array$.length; $i$++) { $type$ $var$ = $array$[$i$]; $end$ }
itco for(Iterator $iter$ = $col$.iterator();$iter$.hasNext();) { $type$ $var$ = ($type$) $iter$.next(); $end$ }
itli for (int $i$ = 0; $i$ < $list$.size(); $i$++) { $type$ $var$ = ($type$) $list$.get($i$); $end$ }
itmk Iterator $iter$ = $map$.keySet().iterator(); while ($iter$.hasNext()) { $type$ $var$ = ($type$) $iter$.next(); $end$ }
itmv Iterator $iter$ = $map$.values().iterator(); while ($iter$.hasNext()) { $type$ $var$ = ($type$) $iter$.next(); $end$ }
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; }
ltoar $type$ $var$ = new $typeelem$[$list$.size()]; $var$ = ($type$) $list$.toArray($var$); $end$
main public static void main(String[] args) { $end$ }
outp out.println($end$);
pral private ArrayList _$end$ = new ArrayList();
prb private boolean _$end$;
prhm private HashMap _$end$ = new HashMap();
pri private int _$end$;
prs private String _$end$;
pusf public static final $end$;
pusfb public static final boolean $end$;
pusfi public static final int $end$;
pusfs public static final String $end$;
ritar for (int $i$ = $array$.length; --$i$ >= 0 ;) { $type$ $var$ = $array$[$i$]; $end$ }
ritli for (int $i$ = $list$.size(); --$i$ >= 0 ; ) { $type$ $var$ = ($type$) $list$.get($i$); $end$ }
sep System.err.println($end$);
sop System.out.println($end$);
sw switch ($end$) { case XXX: { } break; default; { } break; }
try try { $end$ } catch (Exception ex) { ex.printStackTrace(); } finally { }
tag <$tag$> $end$ </$tag$>
wh while ($end$) { }
You can use the Expand/Narrow Selection option to successively expand or narrow a selected block of code, based on Java syntax.
With the file open in the editor, ensure that the editor has focus.
Put the cursor at the point where you want to expand the selection, or select a portion of the code.
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.
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.
Use the Narrow Selection option (or press Ctrl+Shift+Minus) to successively reduce selected code in the same fashion.
You can easily surround Java statements and blocks with coding constructs in the Java Source Editor.
To surround a block of code with a construct:
With the file open in the editor, right-click within a statement, or select a block of code, and choose Surround. Alternatively, you can click the Surround ({ }) icon 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.
In the Surround With dialog, select the coding construct.
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 will automatically add 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 appears that lists all possible matches from the class path. The user 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.
You can organize import statements easily in the Java Source Editor. Set the options for organizing imports to your liking 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. For more information, see Section 17.4.3, "How to Enable Automatic Import Assistance for the Java Source Editor."
To organize import statements in a source file:
With the file open in the editor, right-click and choose Organize Imports.
You can use JDeveloper's editing commands to create and maintain documentation comments.
You can add documentation comments to your source files in the Java Source Editor.
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.
With the code element selected in the Structure window, right-click and choose Add Javadoc Comments.
A template for the documentation comment will be inserted in the file. Add information to the template to describe the element.
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.
From the main menu, choose Tools > Preferences.
In the Preferences dialog, choose the Code Editor > Java > Javadoc page.
Click Add. A tag with the default name new
will be added to the list.
In the Tag Properties box change the name of the tag and set its other properties.
When finished, click OK.
You can update documentation comments in the Java Source Editor.
To update documentation comments in a source file:
In the Structure window, place the cursor on the element for which comments are to be updated.
Right-click and choose Add Javadoc Comments.
Tags will be added to or removed from the documentation comment to reflect changes you have made to the element. Add descriptions for the new tags.
You can validate documentation comments in your source files. The audit will report formatting errors and missing or extraneous tags.
To check documentation comments in a source file:
In the Application Navigator, select the file to be checked.
From the main menu, choose Build > Audit <filename>.
In the Audit dialog, select Javadoc Rules from the Profile dropdown list.
If you want configure the audit, to choose which types of errors to search for or to ignore, click Edit.
The Audit Profile dialog opens.
Click Run.
The results of the audit appear in the Log window.
You can add new Javadoc tags and customize the attributes of some existing tags. 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 customize the options for Javadoc in the Java Source Editor:
From the main menu, choose Tools > Preferences.
In the Preferences dialog, expand the Code Editor node.
Expand the Java node and select Javadoc.
On the Javadoc page, select an item in the Tags list to see its attributes displayed to the right. Tags appearing in bold are customizable.
To add a tag, click Add and fill in the information.
To change a tag's position in the Tags list, select the tag and click the up or down button.
To do this without using the mouse, tab to the button and press the spacebar.
To delete a tag, select it in the Tags list and click Remove.
When finished, click OK.
You can add documentation comments to your source files in the Java Source Editor.
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.
With the code element selected in the Structure window, right-click and choose Add Javadoc Comments.
A template for the documentation comment will be inserted in the file. Add information to the template to describe the element.
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:
In the Application Navigator, select the project.
From the main menu, choose Application > Project Properties, or right-click and choose Project Properties.
The Project Properties dialog opens.
Make changes to the project properties as required.
When finished, click OK to close the Project Properties dialog.
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.
The Quick Javadoc feature looks up the selected entity on the source path and displays the Javadoc comment entered in a popup window. If no Javadoc comment exists for that element, an empty Javadoc comment is displayed. The source code is available if one of the following is met:
To display Javadoc for a code element:
Select the code element.
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.
The Quick Javadoc feature is available when the selected source code meets of the following criteria:
It is on this project's source path.
It is on the source path of a project that the current project depends on.
It is available for a library assigned to this project
It is a part of the JDK in use.
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:
Select the name of the code element.
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.
JDeveloper provides these facilities for building projects:
Make /Rebuild option
Ant
Apache Maven
The Make and Rebuild commands execute standard operations for compiling projects in JDeveloper.
Make project makes all the projects the project depends on (recursively), and then makes the project.
Make project only makes the project but not any of the projects it depends on.
Rebuild project rebuilds all the projects the project depends on (recursively), and then rebuilds the project.
Rebuild project only rebuilds the project but not any of the projects it depends on
Make operations compile source files that have changed since they were last compiled, or have dependencies that have changed. Rebuild operations, in contrast, compile source files unconditionally. You can invoke make on individual source files, on working sets, or on containers such as packages, projects, and workspaces.
If you wish to compile more selectively, you can add an Ant buildfile to a project, define additional targets, and run Ant to make those targets.
You cancel a compilation currently in progress by clicking the Cancel Build icon in the main toolbar. When you click this icon, an error message gets printed to the top row of the Compiler Log window.
In a file's source editor window, right-click and choose Make.
Select one or more projects in the navigator, and click Make in the toolbar.
Select one or more projects in the navigator, and choose a Make item from the Build menu.
Select one or more projects in the navigator, right-click, and choose Make.
Rebuild operations compile all the source files in a project or workspace. Unlike make operations, which recompile only those source files that have changed or have dependencies that have changed, rebuild operations are not conditional.
If you wish to compile more selectively, you can add an Ant buildfile to a project, define additional targets, and run Ant to make those targets.
You cancel a compilation currently in progress by clicking the Cancel Build icon in the main toolbar. When you click this icon, an error message gets printed to the top row of the Compiler Log window.
Select one or more source files in the Navigator, right-click, and click Rebuild (for one file), or Rebuild Selected (for multiple files).
Select one or more projects or workspaces in the navigator, and click Rebuild in the toolbar.
Select one or more projects or workspaces in the navigator, and choose a Rebuild item from the Build menu.
Select one or more projects or workspaces in the navigator, right-click, and choose Rebuild.
JDeveloper provides fast yet complete compiling by analyzing dependencies while building. Dependency checking results in fewer unnecessary compiles of interdependent source files, and thus accelerates the edit and compile cycle.
When you compile using JDeveloper, dependency checking is performed whenever you compile with Make. Make uses a dependency file that is automatically created within JDeveloper.
If you compile from the command line, you create or use a dependency file by specifying the following parameter:
javac -make
<makedepfile>
For each project, you can configure the Java compiler by setting options in the Project Properties. For example, you may not want the compiler may to display compiler messages such as:
Example 18-3 Compiler Messages
Note: Some input files use unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
To configure project properties for compiling:
Right-click a project in the navigator and choose Project Properties from the context menu.
You can also double-click a project node in the Application Navigator.
In the Project Properties dialog, expand the Compiler node.
Expand the Javac node.
Optionally expand the Warnings node.
You can optionally check here first to see which options are turned on by default. For example, if -Xlint:all is turned on, all -Xlint
warnings are turned on.
If you don't want to display the -Xlint:unchecked message shown in Figure 18-0, go to the Turn Individual Message Off section of the Project Properties dialog. This allows you to turn off the display of specific Xlint messages, while continuing to display others by default.
Optionally expand the Turn Individual Messages Off node.
Check the -Xlint Unchecked checkbox.
Close all dialogs and recompile.
Note:
If you want to have all your project files automatically saved before compiling, specify this in the Environment page of the Preferences dialog.
You can specify an encoding scheme to control how the compiler interprets multibyte characters. If no setting is specified, the default native-encoding converter for the platform is used.
Text characters are represented using different encoding schemes. In the Windows environment, these are code pages, whereas Java refers to them as native encodings. When moving data from one encoding scheme to another, conversion needs to be done. Since each scheme can have a different set of extended characters, conversion may be required to prevent loss of data.
Most text editors, including the JDeveloper source editor, use the native encoding of the platform on which they run. For example, Japanese Windows uses the Shift-JIS format. If the source code has been encoded with Shift-JIS and you are compiling it in a US Windows environment, you must specify the Shift-JIS encoding for the compiler to read the source correctly.
JDeveloper supports the character encoding schemes included with your currently installed J2SE.
To set the encoding option, do one of the following:
Within JDeveloper, select Application > Project Properties. In the Project Properties dialog, select the Compiler node.
On the command line, use the javac command with the -encoding
option followed by the encoding name.
Choose an encoding name in one of the two following ways:
Select a name from the Character Encoding dropdown list.
Select "default" from the Character Encoding dropdown list to use the default encoding of your environment.
The Java SDK supported encodings are listed at
http://download.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html
JDeveloper uses the Java Compiler (Javac) to compile Java source code (.java
files) into Java bytecode (.class
files). The resulting bytecode is the machine code for a Java Virtual Machine (JVM). Compiling a Java source file produces a separate class file for each class or interface declaration. When you run the resulting Java program on a particular platform, its JVM runs the bytecode contained in the class files.
Javac compiles the specified Java file and any imported files that do not have a corresponding class file. Unless dependency checking is specified (with the -make
option), the compiler compiles all of the target Java files. For more information, see Section 18.6.1.3, "Understanding Dependency Checking."
When you work inside JDeveloper, the compiler used is Javac. You can adjust compiler options in the Project Properties > Compiler > Option.
The following command line options are supported:
-classpath path
The path used to find classes. It overrides the default CLASSPATH or the CLASSPATH environment variable. Directories are separated by semicolons. For example, to search for the class foo.java in the myclasses directory, you would enter the following:
javac -classpath c:\mydir;c:\jdeveloper\myclasses foo.java (Windows) javac -classpath ~/mydir;/usr/jdeveloper/myclasses foo.java (UNIX)
If you are using the Java 2 platform (the default target is JDK 1.6), then the SYSTEM CLASSPATH is prepended to the CLASSPATH. For the above example, SYSTEMCLASSPATH would look similar to the following:
%JAVAHOME%\jre\lib\rt.jar; %JAVAHOME%\jre\lib\i18n.jar; %JAVAHOME%\jre\lib\sunrsasign.jar; %JAVAHOME%\jre\lib\jsse.jar; %JAVAHOME%\jre\lib\jce.jar; %JAVAHOME%\jre\lib\charsets.jar; %JAVAHOME%\jre\lib\classes; c:\mydir; c:\jdeveloper\myclasses
$JAVA_HOME/lib/rt.jar; $JAVA_HOME/lib/i18n.jar; $JAVA_HOME/lib/sunrsasign.jar; $JAVA_HOME/lib/jsse.jar; $JAVA_HOME/lib/jce.jar; $JAVA_HOME/lib/charsets.jar; $JAVA_HOME/lib/classes; ~/mydir; /usr/jdeveloper/myclasses
If JAVAHOME is not defined, then the JDK defined by the SetJavaHome
in jdev.conf
will be used. If there is no JAVAHOME, then the JDK in the <jdev_install
>/jdeveloper/jdk will be used (if present).
If the target JDK is 1.6 (by using -target 1.6), the SYSTEM CLASSPATH is appended to the CLASSPATH. For the above example it would then look similar to the following:
c:\mydir; c:\jdeveloper\myclasses %JAVAHOME%\lib\classes.zip %JAVAHOME%\classes
~/mydir; ~/usr/jdeveloper/myclasses $JAVAHOME/lib/classes.zip; $JAVAHOME/classes
To change the SYSTEMCLASSPATH use option -sysclasspath or option -bootclasspath.
A semicolon-separated list of paths used to locate required Java files.
A semicolon-separated list of paths used to find the system class files.
Equivalent to -sysclasspath
.
The root directory of the class (destination) file hierarchy. For example:
javac -d C:\JDeveloper\myclasses JavaBean.java
(Windows)
javac -d ~/usr/jdeveloper/myclasses JavaBean.java
(Unix)
causes the class files for the classes defined in the JavaBean.java
source file to be saved in the directory C:\JDeveloper\myclasses\MyPackage
, assuming that JavaBean.java
contains the package statement MyPackage
.
Java files are read from the SOURCEPATH and class files are written to the CLASSPATH directory. The destination directory can be part of the CLASSPATH. The default destination matches the package structure in the source files and starts from the root directory of the source.
Detects usage of deprecated types, fields, and methods within the class they are defined in.
You can specify a native-encoding name (or code page name) to control how the compiler interprets characters beyond the ASCII character set. The default is to use the default native-encoding converter for the platform. For more information, see Section 18.6.1.5, "How to Specify a Native Encoding for Compiling."
For example,
javac -encoding SJIS JavaBean.java
compiles JavaBean.java
and any directly imported Java files that do not have class files. Characters in all source files are interpreted as the Shift-JIS character set for Japanese.
Allows you to override the default value for java.endorsed.dirs, the default endorsed standards JDK classes provided by Sun. In pathlist, separate path names with semicolons.
A semicolon-separated list of paths that overrides the location where the compiler looks for extensions.
Generates debugging information in the class file. It is required to access local variables and other information while debugging the class.
Forces the compiler not to generate debugging information in the class file.
Generates selective debugging information in the class file.
Displays the options for the compiler.
Uses the named dependency file for dependency checking. If the specified file is not found, it will be created.
Maximum number of errors and warnings written to output. Use -1 to represent no limit. The default is 1000.
Displays file names as they are compiled.
When specified with an argument, suppresses the warning associated with the number entered by the user.
Suppresses unused import
statements.
Suppresses partially used impor
t statements.
You can also use -nowarn
in combination with -warn:
to output warnings only for warning 487.
Compiles the program without outputting class files.
Compiles all the source files found in the specified package(s)
Rebuilds specified files regardless of dependencies. Rebuild is assumed unless the -make option is used.
Instructs the compiler to recursively descend into directories when expanding file name specifications containing wildcards.
For example:
javac -recurse foo/*java
might be the equivalent to entering:
javac foo/bar/*java foo/lish/*java foo/lish/lee/*java
The option [level] takes an optional integer argument specifying the maximum recursive level.
For example:
javac -recurse 1 foo/*java
might be the equivalent to entering:
javac foo/bar/*java foo/lish/*java
Note that foo/lish/lee/*java
would not be within the scope of the [level] variable.
Compiles the specified source file name(s).
-source {1.1|1.2|1.3|1.4|1.5|1.6}
By default, the source is compatible with J2SE 1.5, which enables J2SE assertions in the source code. You can enter -source 1.4 if you want the source compatibility to be J2SE 1.4.
Forces the compiler not to use extended precision for intermediate floating point calculations.
-target [1.1|1.2|1.3|1.4|1.5|1.6]
If the target is set to 1.1, the compiler compiles for JSDK 1.1. If the target is set to 1.2, the compiler compiles for Java 2 (JSDK 1.2). If the target is set to 1.3, the compiler compiles for Java 2 v1.3 (J2SE 1.3). If the target is set to 1.4, the compiler compiles for Java 2 v1.4 (J2SE 1.4).
The default target is JDK 6 (J2SE 1.6), consistent with Sun's javac
defaults
This option gives more information about compiling, such as which class files are loaded from where in the CLASSPATH. You get information about:
Which source files are being compiled
Which classes are being loaded
Which classes are being loaded
This option displays SOURCE PATH and CLASSPATH values used by the compiler.
This option allows you to specify warnings. You can have any number of warnings in combination with any suppressed warnings. When used with no arguments, all warnings are displayed. Two useful warnings:
Displays Unused Import Statement
Displays Partially used Import Statement.
A list of javadoc comment tags. If listed tag occurs in source comment, a warning is output. Use a comma to separate tags names.
You have two ways to compile applications (workspaces) and projects:
Inside JDeveloper by using the various Build and Compile options on the application and project nodes
From the command line by using ojmake
and ojdeploy
.
You can find both in the jdeveloper/jdev/bin
directory.
ojmake
can be used for applications and projects that don't involve any deployment, for example, projects with no deployment profile defined.
ojdeploy
can handle the build of any application and project (including any that involve deployment). You can think of it as a super-set of ojmake
.
You can view help for the tools simply by executing ojmake
or ojdeploy
on the command line. The help will display in the console.
Note:
When you work from the command line, it is possible to use Javac to compile Java files, but it's not possible to build applications and projects by executing Javac manually. You must use ojmake
or ojdeploy
.
You can clean your application or project using the Clean command. Running this command cleans the output and deploy directories in your project or application.
Running the Clean command on an application or project removes all class files, all copied resource files, and all deployed files. You can do this to ensure that there are no outdated files in the output and deploy directories. For instance, classes get renamed, moved, or deleted, and obsolete class files belonging to those classes need to be removed. Similarly, resources and deployments also get renamed, moved or deleted, and their obsolete copies in the output directory or deployment directory need to be removed. Cleaning enables you to remove previous build artifacts and start afresh.
You can run the Clean command on applications or projects.
When you clean an application:
The content in the output and deploy directories of each of the constituent projects in the application are deleted.
The content in the deploy directory of the application is deleted.
The content in the deploy directory of the application is deleted.
The following conditions must be satisfied for the Clean command to run successfully:
The output directory of the project to be cleaned, or of each of the projects in the application to be cleaned, must be specified.
The output location must be specified as a directory, and not a file.
The Clean command enables you to remove artifacts left over from previous builds in order to begin a fresh build process.
In the Application Navigator, select the project to be cleaned.
In the Build menu, select Clean project.
In the Cleaning project dialog, click Yes.
To clean an application and all its projects:
In the Application Navigator, select the application you want to clean.
In the Build menu, select Clean All.
In the Cleaning application dialog, click Yes.
You can generate API references and other documentation directly from the navigator, 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 run Javadoc on a package, file, or project:
Select the appropriate node in the navigator.
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.
Apache Ant is a build tool similar in functionality to the Unix make utility. Ant uses XML formatted buildfiles to both describe and control the process used to build an application and its components. Ant supports cross-platform compilation and is easily extensible. Apache Ant is a product of the Apache Software Foundation. For more information, see the website http://ant.apache.org/index.html
.
An Ant buildfile defines targets and dependencies between targets. A target is a sequence of programmatic tasks. When Ant is run to make a target, it first makes other targets on which it depends, and then executes the target's own tasks.
Ant is integrated into JDeveloper. Ant buildfiles can be added to or created for projects. Ant buildfiles can be edited with the XML Source Editor. Ant can be invoked from the user interface to make targets defined in buildfiles.
Ways to run Ant on buildfile targets:
On targets in the project buildfile. A project can contain several Ant buildfiles, but one can be designated as the project buildfile. You can configure the Run Ant on project toolbar icon and dropdown menu to give easy access to the project buildfile's targets.
From the Structure pane when editing an Ant buildfile. When an Ant buildfile is open in an XML source editor, its targets are listed in the structure pane. You can select these and run them.
From external tools you define. Use the Create External Tool wizard to define menu items and toolbar buttons that make Ant targets.
You can invoke Ant from JDeveloper's main menu and toolbar to build targets defined in the current project's project buildfile.
A project can contain several Ant buildfiles, one of which can be designated as the project buildfile. You can configure the Run Ant on project toolbar button and dropdown menu to give easy access to the project buildfile's targets.
To select and configure a project's project buildfile, go to the Ant project properties page (choose Application > Project Properties).
Ways to run Ant on targets in the project buildfile:
From the toolbar, click Run Ant on project.
Ant will make the project's designated default target.
From the main menu, choose Build > Run Ant on project.
Ant will make the project's designated default target.
From the toolbar Run Ant on project dropdown menu, choose a target.
The Ant Log window displays messages specific to the Ant build. Some features of the Ant Log window are:
It displays messages generated by an Ant invocation to build one or more targets.
In the Ant Log window, messages generated by Ant tasks are linked to the definitions of those tasks in the Ant buildfile, while compilation errors and warnings are linked to the source code that produced them.
The color coding indicates the output level of messages.
Apache Maven is a software project management and comprehension tool. Maven can manage a project's build, reporting and documentation from a central piece of information, the project object model (POM). You can build the project using its POM and a set of plugins that are shared by all projects using Maven, providing a uniform build system.Maven can be extended by plugins to use a number of other development tools for reporting or the build process. For more information about Maven, see http://maven.apache.org/index.html
.
The Project Object Model (POM) is an XML file that contains information about the project and configuration details used by Maven to build the project. The XML file contains most of the information required to build a project. Configuration information that can be specified in the POM includes the project dependencies, the plugins or goals that can be executed, and the build profiles.
For more information about the Maven Project Object Model, see: http://maven.apache.org/index.html
Use options in the New Gallery to:
Create a new Apache Maven POM
Create a POM for the Application
Generate a Maven POM from a Project
Choose File > New to open the New Gallery.
In the Categories list, expand General and select Maven.
Select an option for creating a POM and click OK.
You can create a Maven POM based on an existing project that you select in the Application Navigator. Build elements will be added for multiple source directories. Settings will be added for the Java compiler you have specified for the project.
To create a Maven POM from a project:
In the Application Navigator, select the project that you want to create the POM from.
Choose File > New to open the New Gallery.
In the Categories list, expand General and select Maven.
Select Generate a Maven POM from a Project.
Click OK.
You generate a new Project Object Model (POM) for the selected application and optionally, a new POM for each project in the application. This generates a top level POM for the application, and a POM for each project.
To generate a POM from a application:
Choose File, then New to open the New Gallery.
In the Categories list, expand General and select Maven.
Select Create a POM for the Application and click OK.
You can create a:
Maven Application template that is made of one or more Maven projects.
This generates an application, a top level Project Object Model file (pom.xml
) for the application, and a default pom.xml file
for each project.
Maven Project template.
This generates a Java project that includes a default Project Object Model file and Maven Configuration. The Project Object Model file is automatically created during project creation.
To create a JDeveloper Project with a default POM:
Choose File, then New to open the New Gallery.
Select All Items.
Select either Maven Application or Maven Project.
Click OK.
Use the Application Navigator to locate and run a Maven project.
In the navigator, locate the project containing the pom.xml
file you want to run.
The pom.xml
file is typically located in the Resources folder under the project.
Right-click on the pom.xml
file.
In context menu, select Run Goal(s), then select a goal.
The list of goals that displays in the context menu is set using the Maven: Goals properties dialog.
In the Maven project properties dialog, you can specify which version of Maven to use. Maven version 2.0 and above is supported.
In the Application Navigator, locate the project whose properties you want to set.
Right-click on the project name.
Select Project Properties.
Select Maven.
Enter the Maven version you want to use in the Specify Maven Version field.
Use the Maven Project Properties dialogs to specify:
Which Maven version to use
Location of the settings.xml
file
Location of the pom.xml
file
Additional classpath entries
Dependencies
Choices that appear in the Run Goal(s) context menu
Java version
Environment variables
Maven repositories
Command line options
To set Maven project properties:
In the Application Navigator, locate the project whose properties you want to set.
Right-click on the project name.
Select Project Properties.
Select Maven.
Select the name of a properties dialog.
You can create a profile by manually editing an XMI export of a class model.
A Profile owns one or more Stereotypes, that in turn own attributes (Properties), and Extensions, that determine which metaclasses can be extended by a particular stereotype. Profile, Stereotype and Extension have, respectively, exactly the same form as Package, Class and Association so you can use the standard UML support to create XML to use as the basis for the profile.
Create a UML project.
Create a root package called MyProfile
.
Create a class called MyStereotype
.
Create an owned attribute in the class called myAttribute
typed by String
.
Create an owned attribute in the class called base_Class
without a type.
Create an association called A_base_Class_myStereotype
.
Create an owned end called myStereotype
typed by MyProfile::MyStereotype
.
Update the memberEnd
property of the association to also include MyProfile::MyStereotype::base_Class
.
Choose File > Export > UML as XMI.
The file should look something like Example 18-4.
Example 18-4 11.1.2.0.0 Profile Code
<?xml version='1.0' encoding='UTF-8' standalone='yes'?> <xmi:XMI xmi:version='2.1' xmlns:xmi='http://schema.omg.org/spec/XMI/2.1' xmlns:uml='http://schema.omg.org/spec/UML/2.1.1/uml.xml'> <documentation exporter='Oracle JDeveloper' exporterVersion='11.1.2.0.0'/> <uml:Package xmi:id='urn:uuid:e758ac95-c939-437c-b8db-93b614d7a1e6' name='MyProfile'> <packagedElement xmi:type='uml:Association' xmi:id='urn:uuid:bedc874e-54bb-43ac-8118-332da29ee332' name='A_base_Class_myStereotype' memberEnd='urn:uuid:9b0a1dac-f235-4c0f-8d23-5d050869376e urn:uuid:c148a047-b02d-4144-a49d-e1ee6d363ae2'> <ownedEnd xmi:id='urn:uuid:9b0a1dac-f235-4c0f-8d23-5d050869376e' name='myStereotype' association='urn:uuid:bedc874e-54bb-43ac-8118-332da29ee332' type='urn:uuid:61415c2c-2835-42cd-87e7-9d95a8675bc3'/> </packagedElement> <packagedElement xmi:type='uml:Class' xmi:id='urn:uuid:61415c2c-2835-42cd-87e7-9d95a8675bc3' name='MyStereotype'> <ownedAttribute xmi:id='urn:uuid:bae8137e-8efc-4311-9cb6-bac77d25cef1' name='myAttribute'> <type href='http://schema.omg.org/spec/UML/2.1.1/uml.xml#String'/> </ownedAttribute> <ownedAttribute xmi:id='urn:uuid:c148a047-b02d-4144-a49d-e1ee6d363ae2' name='base_Class' association='urn:uuid:bedc874e-54bb-43ac-8118-332da29ee332'/> </packagedElement> </uml:Package> </xmi:XMI>
Add xmlns:cmof='http://schema.omg.org/spec/MOF/2.0/cmof.xml'
to the xmi:XMI
element.
Change the value of the package xmi:id
to '_0'
Add uri='http://example.oracle.com/MyProfile.xmi'
to the uml:Package
element.
Add <type href='http://schema.omg.org/
as a child of the
spec/UML/2.1.1/uml.xml#Class'/>base_Class
attribute.
Substitute uml:Profile
for uml:Package
.
Substitute uml:Stereotype
for uml:Class
.
Substitute uml:Extension
for uml:Association
.
Substitute ownedEnd xmi:type='uml:ExtensionEnd'
for ownedEnd
.
Add <cmof:Tag name='org.omg.xmi.nsURI' value='http://example.oracle.com/MyProfile' element='_0'/>
as a child of xmi:XMI
.
The file should look something like Example 18-5.
Example 18-5 11.1.2.0.0 Profile Code
<?xml version='1.0' encoding='UTF-8' standalone='yes'?> <xmi:XMI xmi:version='2.1' xmlns:xmi='http://schema.omg.org/spec/XMI/2.1' xmlns:uml='http://schema.omg.org/spec/UML/2.1.1/uml.xml' xmlns:cmof='http://schema.omg.org/spec/MOF/2.0/cmof.xml'> <documentation exporter='Oracle JDeveloper' exporterVersion='11.1.2.0.0'/> <uml:Profile xmi:id='_0' name='MyProfile' uri='http://example.oracle.com/MyProfile.xmi'> <packagedElement xmi:type='uml:Extension' xmi:id='urn:uuid:bedc874e-54bb-43ac-8118-332da29ee332' name='A_base_Class_myStereotype' memberEnd='urn:uuid:9b0a1dac-f235-4c0f-8d23-5d050869376e urn:uuid:c148a047-b02d-4144-a49d-e1ee6d363ae2'> <ownedEnd xmi:type='uml:ExtensionEnd' xmi:id='urn:uuid:9b0a1dac-f235-4c0f-8d23-5d050869376e' name='myStereotype' association='urn:uuid:bedc874e-54bb-43ac-8118-332da29ee332' type='urn:uuid:61415c2c-2835-42cd-87e7-9d95a8675bc3'/> </packagedElement> <packagedElement xmi:type='uml:Stereotype' xmi:id='urn:uuid:61415c2c-2835-42cd-87e7-9d95a8675bc3' name='MyStereotype'> <ownedAttribute xmi:id='urn:uuid:bae8137e-8efc-4311-9cb6-bac77d25cef1' name='myAttribute'> <type href='http://schema.omg.org/spec/UML/2.1.1/uml.xml#String'/> </ownedAttribute> <ownedAttribute xmi:id='urn:uuid:c148a047-b02d-4144-a49d-e1ee6d363ae2' name='base_Class' association='urn:uuid:bedc874e-54bb-43ac-8118-332da29ee332'> <type href='http://schema.omg.org/spec/UML/2.1.1/uml.xml#Class'/> </ownedAttribute> </packagedElement> </uml:Profile> <cmof:Tag name='org.omg.xmi.nsURI' value='http://example.oracle.com/MyProfile' element='_0'/> </xmi:XMI>
JDeveloper comes with a set of ready-to-use JavaBeans on the Component Palette. You can also supplement these components by creating new JavaBeans yourself or by installing third-party ones.
JavaBeans Component technology lets you implement your own framework for data retrieval, persistence, and manipulation of Java objects. You can use JavaBeans technology to create reusable software components for building Java applets and Java client applications. In a Java EE application, applets and application clients can communicate with business-tier components directly or indirectly through web-tier components. For example, a client running in a browser would communicate with the business tier through JSP pages or servlets.
Although JavaBeans components are not considered Java EE web components according to the Java EE specification, JavaBeans components are often used to handle data flow between server components and application clients or applets on the client tier, or between server components and a database on the back end.
For more information on JavaBeans, for example, the basic notion of JavaBeans and what makes a bean, see http://download.oracle.com/javase/tutorial/javabeans/
. The tutorial also contains lessons on writing a simple bean, bean properties, manipulating events and other topics.
JavaBeans are the Java building blocks used in the Java Visual Editor to build a program. Each JavaBean represents a program element, such as a user interface object, a data-aware control, or a system facility. You build your program by choosing and connecting these elements.
In order to speed up your UI design work in the future, create JavaBean components such as toolbars, status bars, checkbox groups, or dialog boxes that you can add to the Component Palette and reuse with no (or only minor) modifications
JDeveloper comes with a set of ready-to-use JavaBeans on the Component Palette. You can also supplement these components by creating new JavaBeans yourself or by installing third-party ones.
JavaBeans are objects in the true object-oriented programming (OOP) sense. Because they are true objects, JDeveloper components exhibit the following:
Encapsulation of some set of data and data-access functions.
Inheritance of data and behavior from a superclass.
Polymorphism, allowing them to operate interchangeably with other objects derived from a common superclass.
Each component encapsulates some element of a program, such as a window or dialog box, a field in a database, or a system timer. Visual components must ultimately extend either java.lang.Object
or extend some other class that derives from it such as javax.swing.Panel
. Non-visual JavaBeans components do not have this requirement.
To be recognized and used in JDeveloper, components must conform to the JavaBeans specification.
To be useful in a program, a JavaBean must provide the means by which it can be manipulated or interact with other components. JavaBeans meet this requirement by defining properties, methods, and events.
All components have properties, methods, and events built into them. Some of the properties, methods, and events that components provide are actually inherited from ancestor classes, which means they share these elements with other components. For example, all UI components inherit a property called background
that represents the background color of the component. Each component can also introduce its own unique properties, methods, and events. For example, the Swing Checkbox component has a property called selected
that indicates whether or not this component initially appears checked.
The first step in developing a bean for reuse is to create the JavaBean class. Using the Create Bean dialog, you can either create a new empty bean or extend an existing class to conform to the requirements of the JavaBeans component model.
In the Application Navigator, select the project you wish the bean to be added to.
From the main menu, choose File > New, or right-click and choose New.
In the New Gallery, in the Categories tree, expand General and select Java.
In the Items list, double-click Bean.
In the Create Bean dialog, accept the defaults, enter new values, or use the Browse buttons to navigate to an existing package and superclass.
Click OK.
The BeanInfo class defines a set of methods that allow bean implementors to provide explicit information about their beans. By specifying BeanInfo for a bean component, you can hide methods, specify an icon for the toolbox, provide descriptive names for properties, define which properties are bound properties, and much more.
When you create a bean and install it on the Component Palette, in most cases you will want its properties and events to appear in JDeveloper's Inspector. If you followed the JavaBeans design and naming conventions while creating your bean, all the properties and events you defined, plus all those inherited from superclasses, appear automatically.
However, you may not use the JavaBeans design and naming conventions, or you may have existing classes that don't use them. In addition, you may not want to give the user of your bean access to every property at design time.
To handle these situations, you can create a BeanInfo class that will provide explicit information about a bean to JDeveloper, rather than having JDeveloper derive the information through automatic introspection. You create this class by extending the SimpleBeanInfo
class.
To create a BeanInfo class using the BeanInfo dialog:
In the Application Navigator, select the project you wish the bean to be added to.
From the main menu, choose File > New, or right-click and choose New.
In the New Gallery, in the Categories tree, expand General and select Java.
In the Items list, double-click BeanInfo.
In the Create BeanInfo dialog, choose the bean you want to create a BeanInfo for. The dialog will generate the BeanInfo class name from the bean itself.
Accept the name of the package, or specify a different package to which the BeanInfo should be added.
Click Browse to choose a base class other than SimpleBeanInfo
for the BeanInfo that you want to implement.
Click OK to add the new BeanInfo class to your project.
In the Java Visual Editor, you see an event primarily as the event-handling method that must be implemented in the class that contains the component. For example, suppose you want to place a button named button1
into a container called Frame1
. In addition, you want something to happen when an end user clicks button1
.
To implement the event-handling method
Select button1 in the Frame1 editor.
Navigate to the Event page of the Property Inspector.
Click to the right of actionPerformed
(actionPerformed
is the event generated when a button is pressed).
This creates a default action-listener name, which you may edit.
Double-click the name to direct JDeveloper to create the appropriate method and take you to the method body.
JDeveloper switches to the Frame1
source view and inserts an event-handling method into Frame1
that is called when that event occurs.
The method is called button1_actionPerformed()
by default. The body of the method is initially empty.
Add code into the method to respond to the button press.
The end user sees all of the potential events from button1
listed on the Events page of the Property Inspector. As the component writer, you are responsible for creating the component class in such a way that all the events it generates will appear in the Property Inspector. All the end user must do to use your bean is write the code that fills in the event-handling method.
Behind the scenes, JDeveloper also generates additional code in the Frame1.java
file to handle the other aspects of event listening:
It generates an anonymous inner class for the action adapter that implements the ActionListener
interface.
It instantiates the class in Frame1
.
It registers itself as a listener for the button1 event by calling button1.addActionListener()
.
All of this code is visible in the source, but your primary task is to fill in the event-handling method that the action adapter calls when the event occurs.
The particular type of inner-class event adapters that JDeveloper generates by default are known as anonymous adapters. This style of adapter avoids the creation of a separate (named) adapter class. The resulting code is compact.
Example 18-6 contains code that is generated for an action-performed event using an anonymous adapter:
Example 18-6 Code Generated for an Action-performed Event Using an Anonymous Adapter
button1.addActionListener(new java.awt.event.ActionAdapter() public void actionPerformed(ActionEvent e) { button1_actionPerformed(e); } }} void button1_actionPerformed(ActionEvent e) { // your code to respond to event goes here }
You can control how JDeveloper generates the adapter class by selecting the desired option from the Code Style page of the Project Properties dialog. The standard event adapters have only public- and package-level access, unlike anonymous adapters that have access to all variables in the scope where the adapter is declared.
Example 18-7 contains code that is generated for an action-performed event using a standard class:
Example 18-7 Code Generated for an Action-performed Event Using a Standard Class
// Registers the adapter as a listener to button1. button1.addActionListener(new Frame1_button1_actionAdapter(this)); ... // Adapter class definition. class Frame1_button1_actionAdapter extends java.awt.event.ActionAdapter { Frame 1 adaptee; Frame1_button1_actionAdapter(Frame1 adaptee) { this.adaptee = adaptee; } public voidactionPerformed(ActionEvent e) { adaptee.button1_actionPerformed(e); } } void button1_actionPerformed(ActionEvent e) { // code to respond to event goes here }
JDeveloper generated the code in Example 18-6 using an anonymous inner class. Example 18-7 contains code that is generated for an action-performed event using a standard class. Both ways of using adapters provide the code to handle action-performed events, but the anonymous adapter approach is more compact.
To make standard adapters the default for your projects:
From the main menu, choose Tools > Preferences.
Select the Java Visual Editor node.
In the Event Settings group, select Standard Adapter as an event-handling option.
Choose OK.
Now JDeveloper will generate standard adapters (as opposed to anonymous, inner classes) for its events.
When creating a bean for reuse, you will want to define its events. Once you have defined its events, you will want to select an event-handling adapter.
To make standard adapters the default for your projects:
From the main menu, choose Tools > Preferences.
In the Preferences dialog, select the Java Visual Editor node.
On the Java Visual Editor page, under Event Settings, select Standard Adapter as an event-handling option.
Click OK.
Now JDeveloper will generate standard adapters (as opposed to anonymous, inner classes) for events.
JDeveloper provides the functionality to create a set of custom events and create an EventListener interface and an EventObject class to support those events.
In the Application Navigator, select the project you wish the bean to be added to.
From the main menu, choose File > New, or right-click and choose New.
In the New Gallery, in the Categories tree, expand General and select Java.
In the Items list, double-click EventSet.
In the Create Event Set dialog, in the Name field, enter the name of the event set.
Specify the events you want to create, edit, or remove in the Notifications field.
Click OK to add the new event set classes to your project.
For complex beans, JDeveloper gives you the option of creating a customizer. A customizer allows you to modify the appearance and behavior of a bean within an application builder so it meets your specific needs. Sometimes properties are insufficient for representing a bean's configurable attributes. Customizers are used where sophisticated instructions would be needed to change a bean, and where property editors are too primitive to achieve bean customization.
A simple customizer can edit the entire component at once. Usually a simple customizer presents a dialog box or panel that lets the user set many properties in the same step.
A complex customizer provides an interactive interface to the component user, guiding the user through the steps to customize the component.
For a complex customizer, you might create a wizard that questions the user about how the component should be customized. Based on the user's responses, the customizer edits all affected properties of the component. Whenever a customizer generates an event informing JDeveloper that something happened, JDeveloper generates the appropriate code.
In the Application Navigator, select the project you wish the bean to be added to.
From the main menu, choose File > New, or right-click and choose New.
In the New Gallery, in the Categories tree, expand General and select Java.
In the Items list, double-click Customizer.
In the Create Customizer dialog, in the Name field, enter the name of the customizer.
If you want to add the customizer to a package other than the default package of your project, enter the package name in the Package field or click Browse Packages.
If you want the customizer to extend a class other than the default, enter the class name in the Extends field or click Browse Classes.
Click OK to add the new customizer class to your project.
When you develop a bean, you must think of all the events that the bean should be able to generate.
To make a component capable of firing events:
Determine what kind of event needs to be fired, and either:
Select an appropriate existing event set from the AWT or JFC, or
Create a new event set.
Create event registration methods for the component.
Create an event notification/propagation mechanism for the event: fire
<yourEventName
>Event()
Call the event that is fired and call the event notification mechanism from the key points in your bean where such an event should be sent.
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 revalidate the program to ensure that no errors have been introduced.
Some examples of simple refactoring operations are:
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.
JDeveloper also provides more sophisticated refactoring operations such as:
Extracting an interface from a class by deriving member declarations from selected class members.
Pulling members of a class up into a superclass or pushing members down into a subclass by moving member definitions from one class to another.
Extracting a class replaces a set of fields or methods with a new container object.
Introducing a field, variable, parameter, or constant by replacing a selected expression with a reference to a new element constructed from the expression.
Extracting a method by replacing highlighted consecutive statements with a call to a new method constructed from the statements.
Extracting a method object to create a new method out of an existing block of code (similar to Extract Method) but moving it into a newly created inner class, converting all the local variables to fields of the class.
Introducing a parameter object replaces a set of fields or methods with a new container object.
If the results of the refactoring operation are not as desired, you can undo the refactoring as you would any editing operation, by pressing Ctrl+Z
.
If you rename or move a class using the in-place edit functionality on a diagram, the source code for the class will be refactored 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 18.8.4, "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 18.8.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)
JDeveloper provides a wide range of automated refactoring operations that enable you to enhance code quality in such a way that it does not alter the external behavior of the code, yet improves its internal structure.
To invoke a refactoring operation:
Select a program element in a source editor window, navigator pane, or structure pane.
Right-click on the program element.
Choose an operation from the context menu.
You can also choose Refactor from the toolbar and select a refactoring operation from the drop-down list.
Refactoring context menus reflect the operations that are available in the current context. This is determined by the source element that was at the cursor when you right-clicked. These operations differ from element to element. Therefore, the refactoring context menus contain different items depending on where in JDeveloper you are right-clicking to display the menu.
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
.
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 preview to inspect and modify or exclude selected usages, before causing the rest to be renamed.
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.
Select the element that is to be renamed in one of the two following ways:
In a Java Source Editor, select the name.
In a Navigator or Structure pane, select the name.
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.
In the Rename To box, enter the new name. The name must be valid and not already in use.
Set the depth of the text substitution.
Select Search in Comments to extend the operation to comments, the bodies of documentation comments, and to annotations.
(Package, type, and members elements only.) Select Search in Non-Java files to extend the operation to other types of text files in the project.
Select Preview if you wish to inspect the usages that will be replaced before committing to the renaming operation.
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 18.8.3, "How to Rename a Code Element."
While developing your Java application you can safely delete the definition of a class, interface, method, or field. The deletion will not be performed without your confirmation if the element is still in use.
If the element is in use a log showing the usages will be displayed. Use the list to inspect and resolve the usages. If you then confirm the deletion, any remaining usages will remain in the code as undefined references.
Select the element that is to be deleted in one of the following ways:
In a Java Source Editor, select the name.
In a Navigator or Structure pane, select the name.
Invoke the command in one of the following ways:
From the Main menu or the context menu, choose Refactor > Delete Safely.
Press Alt+Delete.
The Delete Safely dialog displays while the project files are searched for usages.
If the dialog closes, the element has been deleted. If it remains open after performing its search, the element has unresolved usages.
Click View Usages to inspect and resolve the usages. When finished, invoke the command again to delete the element.
Click Ignore to delete the element's definition without viewing the usages.
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 have the option, before committing these operations, of having 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:
If you have made any edits that affect usages, click the Refresh icon in the log toolbar to rerun the usages search.
Click the Do Refactoring icon in the log toolbar.
While developing your Java application you can easily define new classes and interfaces and repurpose existing ones.
When developing your Java application you can easily move a package, class, or interface to a different package. If you wish, you can first generate a preview — 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.
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 navigator or in the Structure window, select the name.
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 Vehicle dialog opens.
In the Move To box, enter the new package name, or click [...] to navigate to an existing package.
Set the depth of the text substitution.
Select Search in Comments to extend the operation to comments, the bodies of documentation comments, and to annotations.
Select Search in Text Files to extend the operation to other types of text files in the project.
Select Preview if you want to inspect the usages that will be replaced before committing to the move operation.
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 18.8.3, "How to Rename a Code Element."
Classes can also be moved in the Application Navigator by dragging multiple classes from one package to another.
While developing your Java application you can easily duplicate a class or interface.
Only primary classes and interfaces — those having the same name as their file — can be selected to be duplicated. The duplicated class or interface is added to the same package as the original.
Member names in the new class are given the same name as those in the original, except for those derived from the original class or interface name. When the original name is embedded in a member name, the new name is substituted.
To duplicate a class or interface:
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.
From the Main menu, choose Refactor > Duplicate.
The Duplicate type dialog opens.
In the Class Name box, enter the new name. You can also specify a new package.
Click OK.
The new class will be added to the project.
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.
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 navigator or in the Structure Window, select the class name.
From the Main menu, choose Refactor > Extract Interface.
The Extract Interface dialog opens.
In the Package field, enter the name of the package of the new interface.
In the Interface field, enter the name of the new interface.
In the Members to Extract table, select the members that will be included in the new interface.
Select Replace Usages if you want to convert existing declarations that name the class into declarations naming the interface.
Select Preview if you wish to inspect the usages before you commit to the operation. This option is enabled only if you have selected Replace Usages.
Click OK.
Otherwise, the interface will be created, and no usages will be replaced.
You can create a superclass based on chosen members of the current class. The superclass will consist of field and method declarations that match the chosen members.
In a navigator, in the Structure window, or in a Java Source Editor window, select the class name.
From the main menu, choose Refactor > Extract Superclass.
The Extract Superclass dialog opens
In the Package Name box, enter the name of the package to which the new superclass will belong.
In the Class Name box, enter a name for the new superclass.
In the Members to Extract table, select the members that will be included in the new interface.
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.
Select Replace Usages if you wish to convert existing declarations that name the class into declarations naming the superclass.
Select Preview if you wish to inspect the usages before you commit to the operation.
This option is enabled only if you have selected Replace Usages.
Click OK.
If you selected Preview, finish the extraction operation from the Preview log window. For more information, see Section 18.8.3, "How to Rename a Code Element."
Otherwise, the interface will be created, and no usages will be replaced.
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.
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 navigator or in the Structure window, select the name.
From the Main menu, choose Refactor > Use Supertype Where Possible.
The Use Supertype dialog opens.
In the Supertypes table, select the supertype that the declarations will be generalized to.
Select Preview if you want to inspect the usages before you commit to the operation.
Click OK.
If you selected Preview, finish the extraction operation from the Preview log window. For more information, see Section 18.8.3, "How to Rename a Code Element."
Otherwise, the substitutions will be made immediately.
You can convert an unnamed inner class (an anonymous class) into a named inner class.
To convert an anonymous class into an inner class:
In a Java source editor window, select the declaration of the anonymous class.
From the main menu, choose Refactor > Convert Anonymous to Inner Class.
The Convert Anonymous to Inner Class dialog opens
In the Class Name box, enter the name to be given to the inner class.
If you want the inner class to be given the static modifier, check the Static box.
To convert the anonymous class into an inner class, click OK.
You can move an inner class to a newly created class at the top level.
Select the inner class name in the structure pane or in a Java source editor window.
On the main menu select Refactor > Move. The Move Inner Class dialog opens.
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.
To create a new class at the top level with the details shown in the dialog, click OK.
While developing your Java application you can easily move member definitions from one class to another.
You can move a class member (for example, a method) to another class.
Select the method name in the Structure window or in a Java Source Editor window.
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.
In the Targets panel, choose the class to which the member will be moved.
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.
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.
Select the method name in the Structure window or in a Java Source Editor window.
From the main menu select Refactor > Move.
The Move Members dialog opens.
In the Target panel, enter or choose the class to which the member will be moved.
For each member that you want to move, ensure that the checkbox to its left in the Members to Extract list is checked.
If you want the dependencies of a member to also be moved, check the corresponding checkbox in the Dependencies column.
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:
Select the method name in the Structure window or in a Java Source Editor.
On the main menu select Refactor > Change Method.
The Change Method dialog opens.
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.
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.
You can assign the static
modifier to a method.
To change a method to a static method:
Select the method name in the Structure window or in a Java Source Editor.
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.
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.
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.
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 navigator or the Structure window, select the name.
From the main menu, choose Refactor > Pull Members Up.
The Pull Members Up dialog will open.
From the Target drop-down menu, choose the superclass that will be the target class.
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.
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.
In the Dependencies column select the checkbox if you wish 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.
Click OK.
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.
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 navigator or the Structure window, select the name.
From the main menu, choose Refactor > Push Members Down.
The Push Members Down dialog opens.
In the Members to Extract table, select the members you wish to push down.
The members that are the dependencies of the selected members, if any, will be indicated.
In the Abstract column, select the checkbox if you wish an abstract definition of the member to be left in the source class.
This selection is transitive. It will cause dependencies of dependencies to also be pushed down.
Click OK.
While developing your Java application you can easily convert expressions into named elements.
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.
In a Java Source Editor, select an instance of the method call that you want to be inlined.
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.
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.
While developing your Java application you can easily 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
.
In the source editor, select the expression.
From the main menu, choose Refactor > Introduce Field.
The Introduce Field dialog opens.
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.
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.
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.
Click OK.
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
.
In the source editor, select the expression.
From the main menu, choose Refactor > Introduce Variable.
The Introduce Variable dialog opens.
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.
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.
Select Declare final if you wish to add the final modifier to the variable's declaration.
Click OK.
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.
In the source editor, select the expression.
From the main menu, choose Refactor > Introduce Parameter.
The Introduce Parameter dialog opens.
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.
A suggested name displays in the Name text box.
You can modify or replace it, or choose another suggestion from the drop-down menu.
Select Declare final if you want to add the final modifier to the variable's declaration.
Click OK.
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.
In the source editor, select the expression.
From the main menu, choose Refactor > Introduce Constant.
The Introduce Constant dialog opens.
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.
A suggested name displays in the Name text box.
You can modify or replace it, or choose another suggestion from the drop-down menu.
Click OK.
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.
In the source editor, select the expression or the sequence of expressions that you wish to extract.
From the main menu, choose Refactor > Extract Method.
The Extract Method dialog opens.
Enter a name for the new method.
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
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.
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.
If you deselected any of the proposed parameters in the Parameters list, edit the new method to initialize its local variables.
You can convert a constructor into a factory method.
To convert a constructor into a factory method:
Select the constructor name in the Structure window or in a Java Source Editor.
On the main menu select Refactor > Replace Constructor With Factory Method.
The Replace Constructor With Factory Method dialog opens.
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.
To convert the constructor into a factory method click OK.
You can change the fields of a class from being publicly accessible to being accessible only from within the class.
Select the field name (or its parent class) in the Structure window or in the Java Source Editor.
On the main menu select Refactor > Encapsulate Fields.
The Encapsulate Fields dialog opens.
In the Fields table, check the box next to each field that you want to be encapsulated.
In this dialog, you can also specify options for method/field accessibilities and the scope for replacements.
Select how you would like accessors to be replaced as part of the encapsulation.
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.
If you want to inspect the changes before you commit to the operation, select Preview.
Click OK.
If you selected Preview, finish the extraction operation from the Preview log window. For more information, see Section 18.8.3, "How to Rename a Code Element."
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.
In the source editor, select the boolean expression.
Right-click on the expression and choose Refactor > Invert Boolean.
Table 18-1 contains an example of an inverted boolean expression.
JDeveloper provides a suite of tools for analyzing the quality and performance of your Java code. Use these tools to improve both the quality of your code and your own programming skills.You can use JDeveloper's Auditing feature to analyze Java code for conformance to programming standards.
Auditing is the static analysis of code for adherence to rules and metrics that define programming standards. Auditing finds defects that make code difficult to improve and maintain. JDeveloper's auditing tools help you find and fix such defects. Code can be audited even when it is not compilable or executable.
A rule is a qualitative test for the presence or absence of some feature. For example, common Java coding style requires that class names be capitalized. A violation occurs when a rule is not adhered to.
A metric is a quantitative measurement of size or complexity. For example, a method that is too long, or covers too many cases should delegate some of its functionality to other methods. An over-threshold anomaly occurs when the specified upper bound is exceeded.
You can create and customize profiles, choose the rules to be used, and set parameters for individual rules. Browse the audit rules and metrics to learn more about them. For more information, see Section 18.9.25, "How to Browse Audit Rules, Code Assists, and Metrics."
Developers's audit and metrics features are extensible. Audit and metrics are two facets of a source code analysis and transformation framework that can be customized and extended. The public API for both audit and metrics is the oracle.jdeveloper.audit
package.
Run the auditor on source files to produce an audit report. For more information, see Section 18.9.6, "How to Run Audit to Generate an Audit Report."
Use Code Assist to audit while editing. Audit violations are highlighted as you edit, and you can apply automated corrections.
Audit from the command line to produce an audit report. For more information, see
The Status window displays audit violations in the document selected in the Active view.
An audit report displays rule violations and measurements organized as a tree. A row of the tree corresponds to either a construct or a violation, and includes any measured values for the construct or theoretical violation. A construct is a method, class, file, project, or workspace.
The following properties are found in the rules:
Default fix
The fix that will be used for violations of this rule are when Apply Default Fix is applied to a construct.
Pattern
A regular expression used as a filter to find unconventional identifiers.
Severity
Use to sort rule violations in the audit report.
Visibility
A threshold based on the accessibility keyword. Violations will be reported only if they occur in classes or methods having at least the chosen visibility.
Audit rules are static, qualitative, analyses of code.
In an auditing profile individual rules can be enabled and configured by setting their properties. When a code construct does not satisfy a rule, a rule violation is reported. Some rules define automatic fixes that you can choose to apply.
Rule | Description |
---|---|
Default Fix |
The fix that will be used for violations of this rule are when Apply Default Fix is applied to a construct. |
Pattern |
A regular expression used as a filter to find unconventional identifiers. |
Severity |
Use to sort rule violations in the audit report. |
Prefix |
A regular expression used to find identifiers with unconventional prefix. |
Visibility |
A threshold based on the accessibility keyword. Violations will be reported only if they occur in classes or methods having at least the chosen visibility. |
Audit metrics are static, quantitative analyses of code.
In an auditing profile individual metrics can be enabled and configured. Metrics are configured by setting a threshold: when a code construct exceeds the threshold, an over-threshold measurement is reported in the audit report.
JDeveloper measures the following metrics:
Depth of Inheritance Tree (DIT)
The depth of the inheritance tree of a class. By convention, java.lang.Object has DIT of 1, a class which directly extends java.lang.Object has DIT 2, and so on.
Number of Statements (NOS)
The size, in Java statements, of a method, class, or other construct.
Cyclomatic complexity (V(G))
The branching complexity of a method. Constructs which enclose methods, such as classes and projects, are assigned the maximum complexity measured for an enclosed method. Values above 10 are generally considered problematic.
You can use auditing tools to view audit reports and to investigate and correct rule violations and over-threshold measurements. A new tab will be created in the Log window when auditing starts, and the audit report will be displayed in it.
Auditing is the static analysis of code for adherence to rules and metrics that define programming standards. Auditing finds defects that make code difficult to improve and maintain. The JDeveloper auditing tools help you find and fix such defects. Code can be audited even when it is not compilable or executable.
An audit report is a set of rule violations and metrics measurements presented as a tree organized into constructs. A construct is a method, class, package, file, project, or workspace. If the audit profile includes rules, the table will have a Severity column that shows the designated severity of the constructs. If the audit profile includes metrics, the table will have an additional column for each metric showing the measurements for the constructs.
To sort the report by the contents of a column, click the column header. To reverse the sort order, click again.
From the Log window toolbar you can perform the operations shown in Table 18-3.
Table 18-3 Audit Window Toolbar Icons
Icon | Name | Description |
---|---|---|
|
Refresh |
Click to rerun the audit on the same selection with the same profile. |
|
Cancel |
Click to terminate a running audit. Note that this may give partial results. |
|
Export |
Click to open the Export Results Dialog, from which you can save the report to a file. You may save the results in XML, HTML, or plain text. |
|
Expand All |
Click to expand all the container nodes in the report, exposing all the rows. |
|
Collapse All |
Click to collapse all the container nodes in the report, hiding all but the top-level constructs. |
|
Group Constructs By |
Click to open the Group By dialog, from which you can specify the types of container constructs that will be shown. Grouping by constructs enables you to organize the results better, track defects and violations quickly, and analyze the results easily. |
|
Fix |
Choose a fix for a rule violation from the dropdown menu. For an individual rule violation, choose among the fixes defined for that violation's type. For a group construct, the only choice is Apply Default Fixes, which applies the default fix defined for its type, if any. |
|
Show Over Threshold Only |
Toggle the display of measurements that are within acceptable limits. The threshold is a settable property of metrics. |
You specify filters to prune the set of Java classes whose violations are shown. You can filter by package names, class names, or both. A filter consists of one or more patterns separated by commas.
A pattern can contain the following special characters:
* matches any number of characters
? matches any single character
! at the beginning of a pattern denotes an exclusion pattern
The set of classes that passes a filter is determined by considering the patterns in order. A non-exclusion pattern adds all classes that match the pattern to the set, an exclusion pattern removes all classes that match the pattern from the set. Table 18-4 contains the filters you can specify
Name | Description |
---|---|
Package |
Enter filter patterns that will apply to all but the last element of fully qualified class names. If this field is empty it has no effect. |
File |
Enter filter patterns that will apply only to the last element of fully qualified class names. If this field is empty it has no effect. |
Apply |
Click to apply the given Package and File filters to the report's rows. |
Clear |
Click to erase the Package and File filters, and to restore the report's rows. |
Select one or more constructs (container nodes) or rule violations (leaf nodes) and right-click to open the context menu. From the context menu you can perform the operations shown in Table 18-5 on the selected constructs or rule violations.
Table 18-5 Audit Window Context Menu Items
Name | Description |
---|---|
Apply Default Fixes |
Choose to apply the default fix, if any, to each selected rule violation or to all the violations in the selected constructs. You can define the default fixes using the Tools > Preferences > Audit: Profiles page. |
Apply <Fix> |
Choose to apply this fix to the selected rule violation in the construct. |
About <Rule> |
Choose to display an explanation of the rule that applies to this rule violation. |
Hide <Rule> Violations |
Choose to remove all violations of the selected rule from the report. |
Show Hidden Violations |
Choose to restore all previously hidden violations. |
Show Over Threshold Only |
Click to toggle the display of measurements that are within acceptable limits. |
Cancel |
Choose to terminate a running audit. |
Refresh |
Choose to rerun the audit. |
Group By |
Choose to open the Group By dialog, from which you can specify the types of container constructs that will be shown. |
Expand All |
Click to expand all the container nodes in the report, exposing all the rows. |
Collapse All |
Click to collapse all the container nodes in the report, hiding all but the top-level constructs. |
Go to Source |
Choose to open the source file at the point of the rule violation. If you wish, you can edit the file and correct the violation. |
Export |
Choose to open the Export Results Dialog, from which you can save the report to a file. |
JDeveloper's auditing tools help you find and fix defects that make code difficult to improve and maintain. You can audit code even when it is not compilable or executable. The focus of an audit is defined by a profile, which is a set of audit rules and metrics.
You can browse the audit rules and metrics to learn more about them. For more information, see Section 18.9.25, "How to Browse Audit Rules, Code Assists, and Metrics."
Create an Audit Profile that specifies the rules, code assists, and metrics used to analyze Java programs. In an Audit Profile, individual rules and metrics can be enabled and configured by setting their properties. When a code construct does not satisfy a rule, a rule violation is reported.
Run the Audit Report.
From the main menu, choose Build Audit.... For more information, see Section 18.9.6, "How to Run Audit to Generate an Audit Report."
You can also audit Java code from the command line by invoking ojaudit.exe, which is included in your JDeveloper installation. For more information, see Section 18.9.5, "Auditing Java Code from the Command Line."
Inspect the completed Audit Report for rule violation. For more information, see Section 18.9.15, "How to Inspect an Audit Report Violation or Measurement."
An Audit Report displays rule violations and measurements organized as a tree. A row of the tree corresponds to either a construct or a violation, and includes any measured values for the construct or theoretical violation. A construct is a method, class, file, project, or workspace.
Fix an audit rule violation manually by editing the source, or for some rules, by selecting an automated fix. For more information, see Section 18.9.16, "How to Fix an Audit Rule Violation.".
If you want to run the audit again, you can modify an audit profile by enabling or disabling rules, code assists, and metrics, or by changing their configuration. For more information, see Section 18.9.22, "How to Modify an Audit Profile."
You can save the finished audit report as an XML file or as a formatted HTML or text file. For more information, see Section 18.9.14, "How to Save an Audit Report." Formats are defined by XSL stylesheet files in the /jdev//audit/stylesheets
directory (this directory is not created until audit is run). To create a custom format, adapt a copy of one of the predefined stylesheet files, and add it to the directory.
You can audit a workspace, a project, or a source file from the command line by invoking ojaudit.exe, which is included in your JDeveloper installation, in the <jdev_install>/jdeveloper/jdev/bin
directory.
ojaudit option... file...
Table 18-6 contains the parameters you can use during the audit.
Table 18-6 Command Line Parameters
Parameter | Description |
---|---|
|
The workspace ( |
- |
Set class path for files to audit, if a project is not being audited. |
|
The character encoding for the report. If absent, the character encoding specified for the project is used (see the Compiler page of the project's Project Properties dialog). |
|
Disable rule in profile. To supply multiple values, repeat this option. |
|
Enable rule in profile. To supply multiple values, repeat this option. |
|
Set the issue severity that the Auditor will regard as failure. |
|
Applies default fixes to the code. This option modifies source files. |
|
Prints help for the command help and exits. |
|
The pathname of the output file. If omitted, output is written to standard output. |
|
(required) The profile to use. It is either one of the profiles defined in JDeveloper (as set in the Audit > Audit Profiles page of the Tools > Preferences dialog), or the path name of an exported Audit profile file. Case and whitespace are ignored when searching for a matching profile. |
|
Print defined profile names and exit. |
- |
The project context to use for parameters that are source files. If all parameters are projects or workspaces, this option is not required. |
- |
Suppresses the copyright message. |
|
Set source path for files to audit, if a project is not being audited |
|
The XSLT stylesheet to apply to the report. The name can either be a style sheet defined in JDeveloper, or a pathname to a style sheet file. If absent, the output will be an XML file. Case and whitespace are ignored when searching for a matching predefined stylesheet. |
|
Print defined style sheet names and exit. |
|
The title to use for the report. If absent when |
|
Causes the title to be omitted from the report. |
|
Causes all execution messages to be displayed. |
- |
Prints the command's version and exits. |
|
The workspace context to use for parameters that are not workspaces. If no workspace is designated, a default workspace is synthesized. |
|
Sets workspace context for files to audit. |
Developer allows you to audit your Java programs and generate an audit report.
To audit Java code in JDeveloper:
In the Application Navigator, select one or more applications, projects, or Java source files. The Audit command also works for selections from other views, such as editors and the Structure window.
From the main menu choose Build then Audit target.
The Audit <File, Project, or Application> Dialog dialog appears.
Choose a profile to use in one of the two following ways:
From the Profile dropdown menu choose a profile to use.
Click Edit to create or modify a profile.
Click Run.
An audit report appears in the Log window, and the audit begins. If you wish to stop the audit, click the stop icon in the log's toolbar.
An object is marked serializable by implementing the java.io.Serializable
interface, which signifies that the object can be flattened into bytes and subsequently inflated in the future.
There is an identifier called serialVersionUID
that enables versioning.
You can run an audit that flags all classes that implement java.io.Serializable but do not also have the serialVersionUID.
From the main menu, choose Tools then Preferences then Audit thenProfiles.
An object is marked serializable by implementing the java.io.Serializable interface, which signifies that the object can be flattened into bytes and subsequently inflated in the future.
To turn off serialization on a field of an object, tag the field of the class of the object with the Java's transient keyword. If a class is marked as serializable, but contains unserializable fields that are not marked as transient, then the class is not serializable. You can run an audit to detect these unserializable fields.
From the main menu, choose Tools then Preferences then Audit then Profiles.
Audit reports are displayed as tabbed panes of the Log window. Use the audit report to investigate and correct rule violations and over-threshold measurements.
Use refresh to rerun an audit using the same profile. You may wish to perform a refresh after you have made changes and fixes to your code.
Click in the Log Window toolbar, or right-click and choose Refresh.
The Export Audit Results dialog is cleared, and a new audit will begin. If you wish to stop the audit, click in the Log's toolbar.
You can rearrange the audit report columns to follow your preferred organization.
To organize audit report columns:
Drag the column headers left or right to your preferred position.
Audit report rows are rule violations or measurements, or groups of violations and measurements. The report is organized as a tree. A row of the tree corresponds to either a construct or a violation, and includes any measured values for the construct or a theoretical violation. A construct is a method, class, file, package directory, project, or workspace.
You can choose the constructs that are shown in the report.
To organize audit report rows:
Click the Group By icon in the Log window toolbar.
The Group By dialog opens.
Select the constructs you wish to see.
Click OK.
Click a column header to sort rows by that column. To reverse the sort order, click again.
You can use a class name pattern filter to hide violations and measurements in classes that do not match the filter.
A filter is a sequence of patterns separated by commas, semicolons, or spaces. A pattern can contain the following special characters:
* matches any number of characters
? matches any single character
! at the beginning of a pattern denotes an exclusion pattern
The set of visible classes is determined by considering the patterns in order. A non-exclusion pattern adds all classes that match the pattern to the set; an exclusion pattern removes all classes that match the pattern from the set. Patterns are matched against classnames.
In the Package box of the audit log window, enter a sequence of patterns that will apply to all but the last element of fully-qualified class names. You can leave this box empty if you specify a File filter.
In the File box, enter a sequence of patterns that will apply only to the last element of fully-qualified class names. You can leave this box empty if you specify a Package filter.
Click Apply.
The report will be redisplayed to show only the selected rows.
Click Clear to delete text from the Package and File boxes.
You can save an audit report as an XML file or as a formatted HTML or text file.
Formats are defined by XSL stylesheet files in the <jdev_install
>/jdev
/< system>/audit
/stylesheets
directory (this directory is not created until audit is run). To create a custom format, adapt a copy of one of the predefined stylesheet files, and add it to the directory.
Click in the Log Window toolbar, or right-click and choose Export.
The Export Audit Results dialog opens. Choose a title, format, and destination for the report, and click OK.
JDeveloper generates a report of all audit rule violations.
To inspect an audit rule violation:
In the audit report, select the construct you wish to view.
Right-click and choose Go to Source, or double-click the construct.
An editor for the source file opens with the cursor positioned at the location of the rule violation or the code element measured
Right-click on a violation or anomaly, and select About to learn more about the rule that has been violated
You can fix an audit rule violation manually by editing the source, or for some rules, by selecting an automated fix.
To manually fix an audit rule violation:
In the audit report, select the rule violation (a leaf node in the Constructs tree).
Right-click and choose Go to Source.
An editor for the source file opens with the cursor positioned at the location of the rule violation.
Edit the code to correct the cause of the violation.
To apply an automated fix to an audit rule violation:
In the audit report, select the rule violation (a leaf node in the Constructs tree).
Right-click, and choose an Apply <Rule> Fix menu item, if any.
or
Click in the Log window toolbar, and choose one of the Apply <Rule> Fix menu items.
You can apply automated fixes to all the rule violations in a construct. Default fixes will be applied to each rule violation in the construct that has a Default Fix
property with a value other than None
.
To fix a construct's audit rule violations:
In the audit report, select the construct (a container node in the Constructs tree.
You can apply default fixes in one of the two following ways:
Right-click, and choose Apply Default Fixes.
Click in the Log window toolbar, and choose Apply Default Values.
You can suppress the display of all the rule violations of a given type in the audit report. It is not possible to suppress individual rule violations.
To hide audit rule violations:
In the audit report, select a rule violation (a leaf node in the Constructs tree).
Right-click, and choose Hide <Rule> Violations.
All of the violations of <Rule> are removed from the audit report. The removed rules are not tallied in their parent construct's summaries. Empty constructs are removed if Show Over Threshold Only is enabled. If not, just the violations are removed.
To restore hidden audit rule violations:
In the audit report, right-click to open the context menu.
Choose Show Hidden Violations.
All of the previously hidden rule violations are restored to the audit report.
Metrics reports display measurements for the constructs in the analyzed code. You can focus the report on over-threshold measurements by hiding the others. The threshold is a settable property of metrics.
To show only over-threshold measurements:
In the Log window toolbar, click the over threshold icon. Click again to show all measurements.
Removed measurements are not tallied in their parent construct's summaries. Empty constructs are removed if Show Over Threshold Only is enabled. If not, just the violations are removed.
An audit profile defines the focus of an audit by specifying the rules, code assists, and metrics that will be used to analyze Java code. While several profiles are predefined, you can create others. You can modify an audit profile by enabling or disabling rules, code assists, and metrics, or by changing their configuration.
Certain audit profiles are used by default with some JDeveloper processes and features.
The Code Assist profile is used by the Source Editor, Status window, Application Overview, and File List.
The Audit While Compiling profile is used at the end of a compile when Audit While Compiling is selected in the Audit page of the Preferences dialog.
The Audit Rules profile is the initial default for the Audit command. However, this is not permanent because the Audit dialog remembers whatever profile was last selected.
JDeveloper allows you to specify the rules, code assists, and metrics used to analyze Java programs.
From the main menu, choose Tools then Preferences.
The Preferences dialog opens.
Choose the Audit - Profiles page.
From the Profile dropdown menu, choose a profile to copy.
Select the rules, assists, and metrics to enable in the new profile. For more information, see Section 18.9.26, "How to Activate and Deactivate Components of an Audit Profile."
Configure the selected rules, assists, and metrics, if desired. For more information, see Section 18.9.27, "How to Set Property Values for an Audit Test."
Click Save As.
Enter a name for the new profile, and click Save.
Note:
Names are not case or space sensitive, though case and space are preserved. If the new name differs only in case or space from an existing name, a warning message appears to inform you of this.
The new profile name is shown in the in the Audit Profiles preferences page's Profile box.
Click OK.
JDeveloper allows you to modify audit profiles you created to analyze Java programs.
To modify an existing audit profile:
From the main menu, choose Tools > Preferences.
The Preferences dialog opens.
Choose the Audit - Profiles page.
From the Profile dropdown menu, choose a profile to modify.
Select the rules, assists, and metrics to enable in the new profile. For more information, see Section 18.9.26, "How to Activate and Deactivate Components of an Audit Profile."
Configure the selected rules, assists, and metrics, if desired. For more information, see Section 18.9.27, "How to Set Property Values for an Audit Test."
Click OK.
To delete an existing audit profile:
From the main menu, choose Tools >Preferences.
The Preferences dialog opens.
Choose the Audit - Profiles page.
From the Profile dropdown menu, choose a profile to be deleted. (You cannot delete the predefined profiles.)
Click Delete.
The profile's name will be removed from the Profile box.
Click OK.
You can import or export audit profiles. This would enable you to share profiles, for example, or to maintain a checked in profile used by ojaudit and a nightly build. Audit profiles are imported or exported as XML files.
To import or export an audit profile:
In the Tools menu, select Preferences to open the Preferences dialog.
In the Preferences dialog, open the Audit - Profiles page
Click Import or Export, and select the profile you want to import or export.
Browse the audit tests to learn more about them.
From the main menu, choose Tools >Preferences.
The Preferences dialog opens.
Choose the Audit - Profiles page.
Select one of the Rules, Code Assists, and Metrics tabs.
In the list tree in the left panel, select a category.
A description of the category will be shown in the Explanation box.
Expand the category and select a rule, code assist, or metric, depending on the tab selected.
A description of the selected item will be shown in the Explanation box, and its properties and settings will be shown in the right pane
Click OK to close the dialog.
Activate and deactivate rules, code assists, and metrics for an audit profile from the Audit Profiles preferences page while creating or modifying the profile.
To activate or deactivate a rule, code assist, or metric:
Select the project in the Application Navigator
Choose Tools then Preferences - Audit - Profiles page.
In the dialog, select one of the Rules, Code Assists, and Metrics tabs.
In the list tree in the left panel, expand the category.
Click the checkbox for a test to activate or deactivate it.
Optionally, configure the rule, code assist, or metric. For more information, see Section 18.9.27, "How to Set Property Values for an Audit Test."
Click OK when you are done.
To activate or deactivate a category:
In the left-hand list, click the checkbox for a rule category to activate or deactivate all the category's items. Clicking on any item in the category while pressing the Ctrl key achieves the same result.
To set an audit rule's property values:
Select the project in the Application Navigator.
Choose Tools then Preferences - Audit - Profiles page.
In the dialog, select one of the Rules, Code Assists, and Metrics tabs.
In the list tree in the left pane, expand a category and select an item.
The test's property names and current values are shown in the right panel.
Change the property values by choosing or entering alternative values.
Click OK when you are done.
The profiler gathers statistics on your program that enable you to more easily diagnose performance issues, such as bottlenecks by identifying methods consuming more time, which method is called the most, how memory is used, and what kind of objects are being created.
The Profiler monitors and logs a running program's use of processor and memory resources. It gathers statistics that enables you to more easily diagnose the performance issues and correct the inefficiencies in your code.
JDeveloper offers two kinds of profilers: The CPU Profiler and the Memory Profiler, for local as well as remote profiling.
The CPU Profiler is used to analyze your application's impact on the processor. Use the CPU Profiler to test functions of your application, such as startup and initialization, repainting, and compiling.
The Memory Profiler provides a visual and statistical analysis of how your program utilizes memory in the Java heap.
Memory profiling displays which parts of the application are using the most memory. It also enables you to investigate which objects are responsible for holding the most memory. The Memory Profiler displays data in three views: Classes and Allocators for new objects/garbage collection reporting, and the References view for heap snapshots.
The Classes view shows new objects/garbage collection data organized by Java class. It is used to discover which classes allocated the most memory.
The Allocators view shows the threadgroups, threads and methods that created the most memory.
The References view contains a hierarchical display of all classes, objects and references to objects in the application heap at the time of the snapshot.
Profilers are invoked from the Run menu. You can use the Profiler pages of the Edit Run Configuration dialog to specify the mode of profiling you would like to analyze your code.
In the dialog, you can also specify how you want to profile your programs, locally or remotely. To profile your program locally, set Profiler Connection Parameters, and to profile your program remotely, set Remote Profiling Parameters in the Profiler page of the Edit Run Configuration dialog.
You can profile your application locally or remotely. In local profiling, you profile your application within JDeveloper by choosing one of the CPU Profile or Memory Profile commands from Run menu, or outside JDeveloper by choosing Attach Profiler from the Run menu. In remote profiling, you run a profiling session remotely. You profile your application external to JDeveloper with, or without, profiler parameters. The application's JVM can be on the same host or on a network.
You can configure options for the CPU and Memory profilers by right-clicking on a project and clicking Project Properties. Click Run/Debug/Profile > Edit > Tool Settings > Profiler to set the options.
You use the CPU Profiler to gather statistics on the performance of your application. The CPU Profiler can be used to test functions of your application, such as startup, initialization, repainting, and compiling.
The CPU Profiler collects sample data on a running application at regular intervals based on the Sample Interval setting, which you can change using the CPU Profiler options page. For more information, see Section 18.10.13, "How to Set Options for the CPU Profiler."
The Profiler provides two CPU profiling options: Sample CPU Time and Count Method Calls. You can use Sample CPU Time to determine the areas of your code which are accounting for the most (or least) execution time. Count Method Calls display which methods are called and the number of times they are called.
Note:
The Profiler does not allow you to sample time and count method calls at the same time. Counting method calls will cost you a high level of CPU time, and also distorts the profiler results.
Counting method calls is the most expensive form of profiling, both in terms of CPU overhead and memory usage, because the process uses extra CPU for every method entry and exit and it collects data for every method that is called during the use case.
The CPU Profiler window displays data that the Profiler returns. It provides several options to view, sort, and organize Profiler results, as well as to begin, label, compare, and end Profiler use cases.
The profiler has two tools for memory profiling: New objects/garbage collection reporting and reference snapshots (also known as heap dumps). Use new objects/garbage collection reporting to find out what parts of an application are using the most memory. Use reference snapshots to find out what objects are responsible for holding the most memory. The options allow you to use both at the same time, but usually you would not need a snapshot unless you have spotted a memory leak, and you would not need another new objects/G.C. report if you are investigating a particular leak.
The Memory Profiler window displays data that the profiler returns. It provides several options to view, filter, sort, and organize Profiler results, as well as to begin, label, compare, and end Profiler use cases
The Profiler itself consumes CPU and memory resources during use. The overhead varies depending on the profiling mode in operation. In general, CPU sampling (with a 20 ms. sample interval) and reference snapshots are the fastest and use the least memory.
Both CPU method call count and memory new objects/garbage collection profiling are much more expensive in terms of CPU and memory in both the Profiler and profilee. This is because they intercept essentially every method call and record per method, per call stack, per thread data.
In the case of reference snapshots, it takes only a few seconds for the Profiler agent to write a snapshot file. All other processing is done outside the application, so memory snapshots have little effect on application performance.
Table 18-7 contains some actual performance times for an application's benchmark.
Table 18-7 Application Benchmark Times
Profile Type | Relative Time | Time (seconds) | Notes |
---|---|---|---|
No profiling |
1.0 |
720 |
|
CPU samples |
1.025 |
738 |
20ms sample rate |
CPU samples |
1.29 |
930 |
10ms sample rate |
Memory new objects/garbage collection |
1.56 |
1125 |
|
Reference Snapshot |
1.02 |
735 |
Table 18-8 contains the numbers produced by a shorter run:
Profile Type | Relative Time | Time (seconds) | Notes |
---|---|---|---|
No profiling |
1.0 |
30.7 |
|
CPU samples |
1.4 |
41.8 |
20ms sample rate |
CPU samples |
1.7 |
51.2 |
10ms sample rate |
Method call count |
4.6 |
141.2 |
With method filter |
Method call count |
6.6 |
201.3 |
No filter |
As the Profiler output is essentially the same for both the 10 and 20 ms. sample intervals, the 20 ms. interval is preferable.
The two tables illustrate that while profiling overhead can vary dramatically for different use cases, CPU samples and reference snapshots are always less expensive than the other alternatives.
In JDeveloper, you can profile a usecase in the default allocated 512MB memory, but some use case require a memory of 1GB or more for new objects/G.C. memory profiling.
The aim of profiling is to discover those parts of an application that use more resources than desired, and improve them so that optimization of resources can be achieved. The process is to find individual commands, transactions, or sequences of actions that are perceived to be slow, use too much memory or leak memory. You then investigate the cause, make changes intended to improve performance, and then measure again to see if the changes had the desired effect.
In the profiler, we call such a command, transaction, or sequence of actions a use case. The profiler is designed to allow you to isolate meaningful use cases and measure them precisely. By default, the profiler measures nothing until you begin a use case and stops measuring when you end the use case. The data displayed is always relative to a given use case.
The toolbar in the profiler tab indicates the current use case status and provides controls to start and stop use cases and navigate between them.
The Begin Use Case icon in the top left of the toolbar is used to start a new use case. The End Use Case icon beside it is used to stop a running use case. When you start a use case, the End Use Case toolbar icon is enabled and the Begin Use Case toolbar icon is disabled.
If you save an active use case, the use case stops immediately; the End Use Case toolbar icon is disabled, and Begin Use Case toolbar icon is enabled.
Both the begin and end use case controls are disabled when:
A use case has ended but is still being processed by the profiler.
The profilee application has stopped running.
The profiler is no longer connected.
You open a saved session.
The Profiler monitors and logs a running program's use of processor and memory resources. It gathers statistics that enable you to diagnose performance issues and correct the inefficiencies in your code.
The steps for profiling a project are:
Set options for the CPU and Memory Profilers. For more information, see Section 18.10.13, "How to Set Options for the CPU Profiler" and Section 18.10.15.3, "How to Set Options for the Memory Profiler."
For example, you can specify if you want the Profiler to sample CPU time usage by your application, or to count method calls. Or you can specify if you want the Profiler to report data on new objects and garbage collection, or to provide a heap snapshot.
Start the CPU or Memory Profiler inJDeveloper. For more information, see Section 18.10.14, "How to Start the CPU Profiler."
You can also run a profiling session remotely. When you start a remote profiling session, the Profiler connects and profiles remote applications as if they were local. For more information, see Section 18.10.16, "Profiling Remotely."
Isolate meaningful use cases in your program and measure them precisely. For more information, see Section 18.10.7, "Understanding Profiler Use Cases."
The Begin Use Case control in the top left of the toolbar is used to start a new use case. The End Use Case control beside it () is used to stop a running use case. When you start a use case, the End Use Case toolbar icon is enabled and the Begin Use Case toolbar icon is disabled.
Inspect the data that the profiler returns. The Profiler windows provide options to view, filter, sort, and organize Profiler results, as well as to begin, label, compare, and end Profiler use cases.
You can also save the results of your Profiling session for later analysis.
After you have completed your Profiling session, you can then use its statistics to more easily diagnose the performance issues and correct the inefficiencies in your code.
The CPU Profiler tabulates and displays statistical data on the performance on your application, either in terms of time usage, or methods called.
The CPU Profiler enables you to profile your code in one of two ways:
Sample CPU Time to identify which parts of an application are taking the most time.
Count Methods Calls to confirm that methods are being called and how many times they are called.
CPU profiling tabulates the processing time spent by each method in your application by displaying Java Platform calls, and counting those method calls. The CPU Profiler displays data in two views: Hotspots and Call Stacks.
The Hotspots view lists all Java platform methods and all methods they call, sorted by time usage in the CPU Profiler's time sampling mode of operation. It also displays the cumulative amount of CPU time spent in each method. During the method call count operation, the Hotspots view shows all the methods and the number of times they were called.
The Call Stacks view, during the CPU Profiler's time sampling mode of operation, lets you view the Java platform methods called in their call hierarchy. In the count method call mode, the Call Stacks view lists the Java platform methods called, sorted by thread group.
The CPU profiler, when used in time sampling mode, analyzes your program and reports results on CPU time usage. The data is displayed in two views: Hotspots and Call Stacks.
The Hotspots view lists all methods sorted by the value of the time spent in them. The hierarchy beneath each method shows the callers of the method, and in turn, their callers, and so on.
The topmost methods in Hotspots are often just noise; the path that the event dispatcher takes to accomplish a task. You can use the Stack Filter to narrow the view down to only relevant methods. Alternatively, you can use the Edit Filter dialog to enter a find or filter expression that will specify the methods to be displayed.
The Call Stacks view lets you see the methods called in their call hierarchy. That is, each level is called by the level immediately above it. Table 18-9 contains the data columns that display in the Calls Stacks View.
Table 18-9 Profiler Data Columns
Column | Description |
---|---|
Name |
Displays the fully qualified method names. |
CPU% |
Displays the percentage of the currently selected data column. For example, if the CPU column is selected, indicated by a downward-pointing triangle, this column is named CPU%. If CPU Shallow column is selected, the column name would be CPU Shallow%. |
CPU (ms) |
Displays the cumulative amount of CPU time spent in seconds, in each method and all the methods it calls. |
CPU Shallow (ms) |
Displays the amount of CPU time spent in each method individually. |
Blocked (ms) |
Displays the cumulative blocked time spent in each method and all the method it calls. The column is available if the Collect Blocked and Wait Time checkbox is selected in the Edit Run Configuration dialog. |
Blocked Shallow (ms) |
Displays the blocked time spent in each method. The column is available if the Collect Blocked and Wait Time checkbox is selected in the Edit Run Configuration dialog. |
Wait (ms) |
Displays the cumulative wait time of each method and all the method it calls. The column is available if the Collect Blocked and Wait Time checkbox is selected in the Edit Run Configuration dialog. |
Wait Shallow (ms) |
Displays the wait time of each method. The column is available if the Collect Blocked and Wait Time checkbox is selected in the Edit Run Configuration dialog. |
Elapsed (ms) |
Displays the cumulative elapsed time of each method and all the method it calls. The column is available if the Collect Elapsed Time checkbox is selected in the Edit Run Configuration dialog. |
Elapsed Shallow (ms) |
Displays the elapsed time of each method. The column is available if the Collect Elapsed Time checkbox is selected in the Edit Run Configuration dialog. |
I/O (ms) |
Displays the cumulative Input/Output time of each method and all the method it calls. The column is available if the Collect IO Time checkbox is selected in the Edit Run Configuration dialog. |
I/O Shallow (ms) |
Displays the Input/Output time of each method. The column is available if the Collect IO Time checkbox is selected in the Edit Run Configuration dialog. |
Note:
If you see more than one top-level method per thread in the Stacks view, the stack depth is too low for your application. To increase the stack depth, you need to update the CPU Profiler options page in the Edit Run Configuration dialog.
The CPU Profiler, when used to count method calls, confirms that methods are being called and tells you how many times. Method call counting is useful when you want to know why a particular method is taking too much CPU time. You can use the Profiler's count method call data to analyze the callers to that method, and edit your code appropriately to reduce the number
You can specify if you want the Profiler to sample CPU time usage by your application, or to count method calls.
In the navigator, double-click the project you want to profile to open the Project Properties dialog.
Click Run/Debug/Profiler.
Click Edit.
In the Edit Run Configuration dialog, set the options as desired on the Tool Settings - Profiler - CPU page.
You can specify if you want the profiler to sample CPU time or count method calls.
When finished, click OK.
Starting a CPU profiling session will automatically run your program. Once the CPU profiler window is open, you can begin a use case to profile your application.
In the navigator, select a runnable node, for example, Application1.java.
From the main menu, choose Run > CPU Profile project
.
If no default run target is specified in the Launch Settings page of the Edit Run Configuration dialog (Application menu > Project Properties > Run/Debug/Profile), the Choose Default Run Target dialog opens. Use this dialog to specify the default run target
Click the Begin Use Case icon to begin a profiling use case.
Note:
If you want to profile your application immediately when the profiler is launched, select the Begin Use Case on Application Startup checkbox in the Profiler page of Edit Run Configuration dialog.
The Memory Profiler enables you to find out how your program is using the Java heap. You can find inefficient heap usage and any suspect memory behavior.
The profiler has two tools for memory profiling: new objects/garbage collection (hereafter referred to as new/G.C. reporting) and reference snapshots (also known as heap dumps). Note the following points while using these tools:
Use new/G.C. reporting to find out what parts of an application are using the most memory.
Use reference snapshots to find out what objects are responsible for holding the most memory.
Memory profiling and method call counts, slows down the system and the application considerably. Note the following points of information before you start profiling an application:
Keep your use cases specific and short.
Wait for the application to start, before you start the use case.
When profiling large applications, JDeveloper requires more than the default memory size. If your applications slows down, navigate to <jdev_install>/jdev/bin directory and try launching JDeveloper from command line with the following command:
jdev -J-Xmx1024m
This command allocates 1 GB of virtual memory to JDeveloper, overriding the default memory of 512 MB.
A web application deployed in Oracle WebLogic Server is considered as a large application. Hence, launch JDeveloper with the -J-Xmx1024m
parameter to increase the memory size before you start profiling.
Some large applications or use cases may fail when profiled in Windows, try profiling such applications or use cases in Linux. Windows operating systems limit the contiguous virtual memory for JVM, but there is no such limitation in Linux.
The Memory Profiler displays data in three views: Classes view, Allocators view for new/G.C. reporting, and the References view for heap snapshots.
The Classes view shows new objects/garbage collection data organized by Java class. It is used to discover which classes allocated the most memory. You can switch to this view by clicking the Classes tab at the bottom of the Memory Profiler.
The Allocators view shows the threadgroups, threads, stacks, and methods that created the most memory. You can switch to this view by clicking the Classes tab at the bottom of the Memory Profiler.
The References view contains a hierarchical display of all classes, objects and references to objects in the application heap at the time of the snapshot.
A reference snapshot is a hierarchical display of classes, objects and references to objects in the application heap at the time of the snapshot. There are two fundamental kinds of references: references from JVM garbage collection roots to objects, and references from one object to another.
JVM garbage collection roots include references from an active thread, references from JNI local and global variables, and internal JVM references. These are the references that keep objects in memory; if there is no path from a gc root to an object, it is eligible for garbage collection. The snapshot contains only objects that are reachable from one or more JVM gc roots.
Note that static references and references from class loaders are not garbage collection roots. A class loader can be garbage-collected when there are no more references to the class loader, any classes loaded by the class loader or any objects of these classes. When a class loader is garbage collected, all classes it has loaded are also garbage collected, as well as all objects that are only referred to by static references from these classes.
There are four types of references from objects to objects: normal (strong) references, soft references, weak references and pseudo references. When you are looking for memory leaks, you normally only care about strong references. You can toggle between viewing only strong references, or all references.
New and old references in different snapshots are indicated using different font styles. When you compare two memory snapshots, the methods in the current snapshot show up in boldface font. If there are methods that are also in the other snapshot, they are shown in bold-italic font in the current snapshot.
There are several ways to compare reference snapshots. In the Memory Profiler References view, for example, you can choose Compare With to select a different use case (snapshot) from the current one. Or, if you have two profiler tabs open (for example, if you have opened a saved profile session) select Compare With and Other, then choose a use case from another session.
You can specify if you want the Profiler to sample CPU time usage by your application, or to count method calls.
To set memory profiler options:
In the navigator, double-click the project you want to profile to report data on new objects and garbage collection, or to provide a heap snapshot.
Click Run/Debug/Profiler.
Click Edit.
In the Edit Run Configuration dialog, set the options as desired on the Tool Settings - Profiler - CPU page.
You can specify if you want the profiler to collect new objects/garbage collection data, take a heap snapshot, or do both.
When finished, click OK.
Starting a Memory profiling session also automatically runs your program. Once the Memory profiler window is open, you can begin a use case to profile your application.
In the navigator, select a runnable node.
From the main menu, choose Run > Memory Profile project
.
Click the Begin Use Case icon to start the profiling session.
You can run a profiling session remotely. When you start a remote profiling session, the Profiler connects and profiles remote applications as if they were local. Since you still run the Profiler locally, you can profile applications on other computers provided that they have a reachable IP address or DNS name.
The main difference between remote and local profiling is the way in which you begin the profiling session. For local profiling, JDeveloper automatically launches the program that you want to profile (the profilee) and then attaches the Profiler to that program. For remote profiling, you must manually launch that profilee program and attach the Profiler later. Once the profilee is launched and the JDeveloper Profiler is attached to it, remote profiling is no different from local profiling. Remember that you can use remote profiling whether or not the profilee process is running on the same machine as JDeveloper.
Note:
If you are profiling your application remotely, you can start your external application with or without profiler parameters. An application started with profiler parameters can have JVM can be on the same host (local) or on a network. An application started without profiler parameters must have JVM on the same host, and you may attach the profiler later.
Remote profiling and local profiling each have advantages over the other. When you remote profile, the Profiler and profilee can be run on two different computers so that they are not competing for the same resources. However, transferring large amounts of data over a network could make profiler performance significantly slower.
To profile remotely in JDeveloper, you invoke the profiler agent. The JDeveloper profiler agent supports 32- and 64-bit JVMs in Windows and Linux. You specify a JVM for a project using the Edit Run Configuration - Launch Settings page.
The names of the profiler agent files are based on the supported architecture and JVM size:
profiler_x32.dll
profiler_x32.so
profiler_x64.dll
profiler_x32.so
If you launch the profilee from JDeveloper, the profiler automatically detects the size of the JDeveloper JVM.
On Linux, it should use API to detect which of 32-bit or 64-bit architecture remote JVM is and use appropriate agent. (This can be generalized to support additional architectures.)
On Windows, it should use API to detect which of 32-bit or 64-bit architecture remote JVM is and, if it is not the same as JDev JVM architecture, not show it in the list of available JVMs to attach
If you attach locally and the JDeveloper JVM is 32-bit, the profiler attempts to load the 32-bit agent and if that fails, tries to use the 64-bit agent. If the JDeveloper JVM is 64-bit, the profiler only tries the 64-bit agent.
To profile a program remotely in JDeveloper, you must start the Java process from the command line. From the command line, you also invoke the Profiler Agent. Once the process has started, you can connect the JDeveloper Profiler to the Profiler Agent.
You can invoke the Profiler Agent using the -agentlib
or -agentpath
option.
To invoke the Profiler Agent using the -agentlib option:
At the command line, enter the following execution string:
java -agentlib:<Profiler-Agent-Library>=<sub-option1>[=<value1>],<sub-option2> [=<value2>]... -classpath -classpath <Project_Directory>\classes <Java_Main_Class>
Note:
While specifying the -agentlib, you may specify the absolute path of the agent excluding the .dll extension, or add the agent's path to your PATH variable and then specify the agent without absolute path and extension.
java -agentlib:C:\JDeveloper\jdeveloper\jdev\lib\ profiler_x32=jarpath=C:\JDeveloper\jdeveloper\jdev\lib\ profiler-agent.jar,port=4000,enable=t,startup=connect -classpath c:\MyApp\MyProject\classes MyMainClass
set PATH=C:\JDeveloper\jdeveloper\jdev\lib;%PATH% java -agentlib:profiler_x64=jarpath=C:\JDeveloper\jdeveloper\jdev\lib\profiler-agent.jar,port=4000, enable=t,startup=connect -classpath c:\MyApp\MyProject\classes MyMainClass
To invoke the Profiler Agent using the -agentpath option:
At the command line, enter the following execution string:
java -agentpath:<Path_to_Agent_Library>=<option1>[=<value1>],<option2>[=<value2>]... -classpath <Project_Directory>\classes <Java_Main_Class>
where
<Path_to_Agent_Library>
is the full path to the profiler_x32.dll
or profiler_x64.dll
. For example, <jdev_install>\jdeveloper\jdev\lib\profiler_x32.dll
.
Note:
While specifying the -agentpath, you must specify the absolute path to the agent including the.dll
extension.
-agentpath:C:\JDeveloper\jdeveloper\jdev\lib\ profiler_x32.dll=jarpath=C:\JDeveloper\jdeveloper\jdev\lib\ profiler-agent.jar,port=4000,enable=t,startup=connect,depth=1000,interval=20 -classpath c:\MyApp\MyProject\classes MyMainClass
Table 18-10 contains the suboptions that are available with the -agentlib
and -agentpath
options.
Suboption | Description |
---|---|
|
Specifies the port over which the data will be transferred. Defaults to 4000. |
j |
Path to profiler JAR file. This JAR is located at |
|
Enables agent capabilities.
Only one of t, c or m may be specified. r may be specified in combination with m or by itself. |
|
If a use case is to begin on startup, you may specify one of the following:
It is not possible to have a use case running unless the profiler is connected.
|
|
Sets maximum stack depth used for collection. Defaults to 1000. |
i |
Sample interval in milliseconds. Defaults to 20. This is only applicable to CPU time sampling. |
|
Report wait and blocked times. Default is n. This is only applicable to CPU time sampling. |
|
Sets the path used to write reference snapshot files. Required if The same path is used for all snapshots, so it is important that the file be copied before the next use case ends. The profiler and file client do this automatically. |
|
Specifies classes to include or exclude in stack traces. For example:
This expression will ensure that no reported stack trace contains any class whose name begins with |
|
Collects only stacks containing the specified methods specified in the expression. For example:
This expression will ensure that no stack will appear unless it contains at least one call to |
|
Object classes to include or exclude from memory reports. For example:
This expression will ensure that no class that contains java.lang in its string will be displayed. |
java
-agentlib:profiler_x32=port=4000,
jarpath=C:\JDeveloper\jdeveloper\jdev\lib\profiler-agent.jar,enable=t,depth=1000,startup=time,interval=20 -classpath
C:\JDeveloper\jdeveloper\mywork\Application1\Project1\classes project1.Application1
java
-agentlib:profiler_x64=port=4000,
jarpath=C:\JDeveloper\jdeveloper\jdev\lib\profiler-agent.jar,enable=m,startup=connect -classpath C:\JDeveloper\jdeveloper\mywork\Application1\Project1\classes project1.Application1
java
-agentlib:profiler_x32=port=4000,
jarpath=C:\JDeveloper\jdeveloper\jdev\lib\profiler-agent.jar,startup=connect,mem -classpath
C:\JDeveloper\jdeveloper\mywork\Application1\Project1\classes project1.Application1
java
*
-agentpath:C:\JDeveloper\jdeveloper\jdev\lib\profiler_x64.dll=
jarpath=C:\JDeveloper\jdeveloper\jdev\lib\profiler-agent.jar,port=4000,enable=t,startup=connect,depth=1000,interval=20 -classpath C:\JDeveloper\jdeveloper\mywork\Application1\Project1\classes project1.Application1
To profile a program remotely in JDeveloper, you must first start the Java program session and invoke the Profiler Agent. For more information, see Section 18.10.18, "How to Invoke the Profiler Agent."
Once the session has started, you can connect the JDeveloper Profiler to it. Connecting the Profiler involves first preparing JDeveloper for remote profiling.
To set up a remote profiling session:
In the Application Navigator, select the project to be remotely profiled.
Select a run configuration and click Edit. For more information, see Section 19.3, "How to Configure a Project for Running."
In the Remote page under Profiler node, select the process type as local or remote.
Click OK when you are done.
Start the Java program session, if you have not already. For more information, see Section 18.10.18, "How to Invoke the Profiler Agent."
In the Application Navigator, select the project to be remotely profiled.
From the Run menu, attach the profiler to CPU Profile or Memory Profile, as desired.
In the Attach Profiler to Running JVM dialog, confirm that Attach to Remote Process option is selected and host/port information is correct.
Click OK.
In the Profiler tab, click Begin Use Case to start profiling a use case.
When you are done, detach the profiler. From the Run menu, select Detach.
Note:
The Connect on Application Startup and Begin Use Case on Application Startup checkboxes in the Profiler page of the Edit Run Configuration dialog have no impact if you attach the profiler to a local process. The checkboxes are applicable when you attach profiler to a remote process only.
JDeveloper allows you to dynamically attach and detach a profiler to a running process. This is similar to profiler attached remote profiling, but doesn't require you to specify profiler parameters on the command line when you launch the application. For example, if you are running an application with no plan to profile it when you started it, but later you wish to profile it because it is exhibiting some performance problems. In such a scenario, dynamically attaching a profiler to a running process saves you from restarting your JVM to attach a profiler to it.
Dynamically attaching a profiler has its limitations too. You can do CPU time sampling or take memory reference snapshots (heap dumps), but you cannot do method call counts or new/gc memory profiling as they require byte code instrumentation, which can only be requested on the command line before the JVM is launched.
To dynamically attach/detach the profiler to a running process:
Start the program outside of JDeveloper, for example, in a different command window.
Open JDeveloper and open the Attach Profiler to Running JVM dialog (Run > Attach Profiler > CPU Profile or Memory Profile).
In the Attach Profiler to Running JVM dialog, select the Attach to Local Process option.
From the list of JVMs, select the program's JVM running on the local system.
Click OK. The profiler connects to the running JVM.
To detach profiler from a running process, select Detach from the Run menu. If you disconnect the profiler by closing the Profiler tab, you cannot reattach to it. To reattach later, you must use Detach command.
To reattach the profiler to a process:
You can detach and attach the profiler to a process as many times as you want, but you must remember the following points before reattaching:
Ensure that profiler is detached before reattaching it again.
When you reattach the profiler, you start a new profiler session, and the data of previous session is lost. To save data of previous session, select Save As from the File menu.
When you reattach profiler to a process, you can change your configuration settings and reattach with the new configuration settings. For example, if you are profiling CPU, you can change CPU configuration to enable or disable collect I/O time, CPU time, wait time, and so on. If you are memory profiling, you can reattach profiler to take heap dumps. You can also switch back and forth between CPU profiling and memory profiling.
However, you cannot reattach if you change your CPU profiling configuration to count method calls, or memory profiling configuration to New/gc. These require capabilities the profiler cannot acquire after the application starts running. To do either of these, you must launch the application with appropriate profiling parameters and attach profiler using the Attach to Remote Process command.
The Profile Points allow you to set a method filter on a method or class. This means that only stacks that contain those methods, or classes, are reported by the profiler. It is used to filter data so you only see a method, what calls it, and what it calls.
pen the file in the source editor, and right-click in the left margin next to a line of executable code.
From the context menu, choose Toggle Profile Point. The profile point icon is displayed on the left margin of the parent class or method name.
You can disable a profile point in any of the following ways:
In the source editor, right-click the profile point symbol in the left margin and choose Disable Profile Point.
In the Profile Point window (View > Profile Points) right-click the profile point you want to disable and choose Disable.
To disable all current profile points, right-click in the Profile Points window, and choose Disable All from the context menu.
When you no longer need to examine the code at a profile point location, you can delete the profile point. You can delete a profile point in any of the following ways:
In the source editor, right-click the profile point symbol in the left margin and choose.
In the Profile Point window (View, then Profile Points) right-click the profile point you want to remove and choose Delete.
To remove all current profile points, right-click in the Profile Points window, and choose Delete All from the context menu.
The profiler allows you to save output for later viewing and analyzing.
To save a running profiler session to disk, in the File menu, select Save As. In the Save As dialog, enter an appropriate name to describe your session, for example, uianalysis.opr
, or accept the default.
Note:
If you are saving an active use case, it will be automatically terminated. The End Use Case toolbar icon is disabled, and Begin Use Case toolbar icon is enabled.
To open a saved profiler session, in the File menu, select Open, and navigate to the session you want to view.
A saved session is visually distinguishable from an active session by its unique profiler icon. In a saved session, the use case begin and end icons are disabled, but the use case navigation controls are active when multiple use cases are available.
JDeveloper allows you to open heap dumps in HPROF binary format and display them in the profiler. HPROF binary format heap dumps can be created by the HPROF profiler, by the JDK tools jmap and jconsole, or through the Java parameter -XX:+HeapDumpOnOutOfMemoryError
.
For example, to create the HPROF file using the jmap command, you could enter on the command line:
jmap -dump:format=b,file=heap.hprof <jdev process id>
For more information about HPROF, see http://java.sun.com/javase/reference/index.jsp
From the File menu, select Open.
Browse and select the HPROF binary format file, and then click Open.
The heap dump opens in the profiler References editor tab.
Note:
Opening large heap dumps is a slow process and may take several minutes to open. On Windows XP, the Profiler cannot open large (> 990MB) HPROF files.
A Java class diagram allows you to visually create classes, interfaces, enums, and inheritance and composition relationships, and to view existing Java classes and interfaces. If you want to visualize a particular facet of your application, add only the classes that contribute to that aspect to the diagram.
To model Java classes you should start with a Java class diagram, although you can subsequently add other elements to the diagram. For more information, see Section 18.11.10, "How to Create a Diagram of Java Classes." You can create and modify the classes that comprise your application directly through the diagram. Changes made on the Java class diagram are immediately available in the Java source editor, and vice versa.
Dependencies are represented on the diagram as a dashed line with an open arrowhead in the direction of the dependency and are used for documentation purposes only and do not change the underlying Java code.
Java classes, interfaces, or enums are created on a diagram by clicking on the Java Class icon, Java Interface icon or Java Enum icon on the Java Component Palette for the diagram, and then clicking on the diagram where you want to create the class. The Java source file for the modeled class or interface is created in the location specified by your project settings.
Java Class, Java Interface, and Java Enum icons are represented on a diagram as rectangles containing the name and details of the Java class. Java classes and interfaces are divided into compartments, with each compartment containing only one type of information.
An ellipsis (...) is displayed in each compartment that is not large enough to display its entire contents. To view a modeled class so that all the fields and methods are displayed, right-click the class and choose Optimize Shape Size, then Height and Width.
Each type of class on a diagram is identified by a stereotype in the name compartment. This is not displayed by default.
Members (fields and methods) display symbols to represent their visibility. The visibility symbols are: + Public, - Private, # Protected. If no visibility symbol is used, the field or method has package visibility.
An interface is normally used to group together method signatures for groups of methods that together define a coherent service. Classes that want to provide the service defined by an interface do this by implementing the interface. Interface names must be unique within a namespace. Because interfaces can be used to specify a set of services that other classes provide, they can be used to enforce some level of consistency on those other classes.
Note:
Modeled Java interfaces can inherit from other interfaces using extends relationships.
For more information, see Section 18.3.6, "How to Create a New Java Interface."
A diagram can include primary or inner classes from different packages, the current application, or from libraries. Inner Java classes and inner interfaces are defined as members of their 'owning' class. Hence, they are also referred as member classes.
Inner classes and inner interfaces are displayed in the inner classes compartment of the modeled Java class or interface on the diagram. Inner classes are prefixed with the term Class, and inner interfaces are prefixed with the term Interface, between the visibility symbol and the class or interface name.
To create an inner class or inner interface on a modeled Java class or interface, either add the inner class to the implementing Java code, or create a new Java class or interface as an internal node on an existing modeled class.
Inner Java classes and inner Java interfaces cannot have the same name as any containing Java class, Java interface or package or contain any static fields or static methods.
A variety of references (previously referred to as associations) can be created quickly between classes and interfaces on a diagram using the various reference icons on the Java Class component palette for the diagram. References created between modeled Java classes are represented as fields in the source code of the classes that implement the references. Compositional relationships are represented on the diagram as a solid line with an open arrowhead in the direction of the reference. Table 18-11 displays the references that can be modeled on a diagram.
Table 18-11 References Between Classes or Interfaces
Reference | Description |
---|---|
Reference (Object) |
A singular, direct reference from one class or interface to another. This is represented in the code of the reference's originating class as a field of type |
Reference (Array) |
A reference to an array of another class or interface. This is represented in the code as an array of type |
Reference (Collection) |
This is represented in the code as a Collection declaration, and adds an |
Reference (List) |
This is represented in the code as a List declaration, and adds an |
Reference (Map) |
This is represented in the code as a Map declaration, and adds an |
Reference (Set) |
This is represented in the code as a Set declaration, and adds an |
Note:
If you want to quickly change the properties of a reference on a diagram, double-click it to display the Code Editor and change the details of the reference.
Labels are not displayed on references by default. To display the label for a reference, right-click the reference and choose Visual Properties, then select Show Label. The default label name is the field name that represents the reference. If you select this label name on the diagram and change it, an @label <label_name>
Javadoc tag will be added before the field representing the reference in the code.
You can change the aggregation symbol used on a reference on a diagram by right-clicking the reference, choosing Reference Aggregation Type, then choosing None, Weak (which adds an @aggregation
shared Javadoc tag to the code representing the reference), or Strong (which adds an @aggregation
composite Javadoc tag to the code representing the reference). Aggregation symbols are for documentary purposes only.
Inheritance structures, which are represented in the Java source as extends
statements, can be created on a diagram of Java classes using the Extends icon on the Java Class Component Palette for the diagram. Extends relationships are represented on the diagram as a solid line with an empty arrowhead pointing towards the extended class or interface.
Where an interface is implemented by a class, this can be created using the Implements icon on the Java Component Palette for the diagram. Creating an implements relationship adds implements
statement to the source code for the implementing class. Implements relationships are represented on the diagram as a dashed line with an empty arrowhead pointing towards the implemented Java interface.
Extends relationships model inheritance between elements in a class model. Extends relationships can be created between Java classes and between Java interfaces, creating an extends statement in the class definition. Enums cannot extend other classes, or be extended by other classes.
Note:
As multiple class inheritance is not supported by Java, only one extends relationship can be modeled from a Java class on a diagram. Multiple extends relationships can be modeled from a Java interface.
Implements relationships specify where a modeled Java class is used to implement a modeled Java interface. This is represented as an implements keyword in the source for the Java class. Implements relationships are represented on class diagrams as dashed lines with an empty arrowhead pointing towards the interface to be implemented. Enums cannot implement interfaces.
If the implemented interface is an extension (using an extends relationship) of other modeled interfaces, this is reflected in the Java source code for the interface.
A class that implements an interface can provide an implementation for some, or all, of the abstract methods of the interface. If an interface's methods are only partially implemented by a class, that class is then defined as abstract.
You can create members (fields and methods) of a Java class or interface on a diagram. The fields and methods are added to modeled Java classes and interfaces on a diagram by double-clicking the modeled Java class or interface then adding the field or method using the Java Source Editor.
Fields are used to encapsulate the characteristics of a modeled Java class or Java interface. All modeled fields have a name, a datatype and a specified visibility.
When a field or method is displayed on a class on a diagram, it is prefixed with + (if declared as public), - (if declared as private) or # (if declared as protected). Static fields are underlined on the diagram.
Methods are defined on a class to define the behavior of the class. Methods may have return types, which may be either a scalar type or a type defined by another class.
A package is a general purpose mechanism for organizing elements into groups. It may contain many different types of elements including packages, files, classes and model elements (for example; classes, interfaces, entity objects). Packages may be nested within other packages.
A package owns the elements within it and provides the context and namespace for those elements. Elements owned by the same package must have unique names within the package. Each element is directly owned by a single package, but can be referenced (imported) from other packages; in other words, referred to by other elements in other packages.
If a package is renamed on a diagram, or moved to another package, the contents of the moved or renamed package will be refactored automatically to reflect this package change.
Package names must be unique within a namespace, even if the names have different capitalization.
Java packages can be either created on a diagram, or dragged onto a diagram from the navigator. To open a diagram for a Java package, right-click the package on the diagram and choose Drill Down.
Java classes and interfaces related to those currently displayed on the diagram can be brought onto the diagram. This includes classes or interfaces that are extended, implemented, or referenced by the selected class or interface.
Note:
Where classes are added to a diagram from the project's source path, and are not already part of the project, those classes are automatically added to the current project.
To display related classes on a diagram, use one of the two following ways:
Select the class or interface, on the diagram, for which you want to display related elements, then choose Model > Show > Related Elements.
Right-click the class or interface, on the diagram, for which you want to display related elements, then choose Show > Related Elements.
Relationships between Java classes or interfaces can be visualized on a diagram using references. You can hide a reference on a diagram.
To hide a reference between Java classes:
Right-click the reference you want to hide and choose Hide Reference.
To display a hidden reference between Java classes:
Double-click the modeled Java class in which the field representing the reference is defined.
Click the Source tab at the bottom of the editor window.
Remove the attribute
Javadoc tag from above the member representing the reference.
The hidden reference will be displayed on the diagram.
Note:
Hiding a reference between Java classes on a diagram adds a comment to the Java source for the class, so if this class is also on any other diagrams, that reference will also be hidden on those diagrams.
The definitions of the classes on a diagram, their members, inheritance, and composition relationships are all derived directly from the Java source code for those classes. These are all created as Java code, as well as being displayed on the diagram. If you change, add to, or delete from, the source code of any class displayed on the diagram, those changes will be reflected on those classes and interfaces on the diagram. Conversely, any changes to the modeled classes are also made to the underlying source code. Some information relating to composition relationships, or references, captured on a Java class diagram is stored as Javadoc tags in the source code.
A Java class diagram can contain shapes from other diagram types (Oracle ADF Business Components, UML elements, Enterprise JavaBeans, and database objects). A form of UML notation is used to display the classes on your diagram. Modeled UML classes can be transformed to modeled Java classes. Likewise, modeled Java classes can be transformed to modeled UML classes. You can annotate a diagram of Java classes using notes, dependency relationships and URL links.
Java classes, interfaces, and enums can be visually created on a Java class diagram, together with their members, inheritance and composition relationships.
You can create UML classes, UML use cases, offline database objects, business components, Enterprise JavaBeans, and web services on a Java class diagram.
Java classes on a diagram must have valid Java class names and must be unique within the class's package. If you define a modeled Java class as abstract you should create a concrete Java class with a generalization to the abstract Java class. The names of modeled abstract Java classes are displayed in italics.
To create a diagram of Java classes:
Create a new diagram using the Java Class Diagram icon in the New Gallery.
Create the nodes you require on the diagram using the Java Class Component Palette.
Also, Java classes and interfaces available to the current project can be dragged from the navigator and dropped on the diagram to either modify the code for those classes, or to visualize the structure of existing code.
Tip:
You can also annotate your diagram by creating and attaching notes to diagram elements, and adding URL links to other locations such as files or web locations.
JUnit is an open source regression testing framework for Java. Use JUnit to write and run tests that verify Java code. For detailed information about JUnit, visit the JUnit website, http://www.junit.org/
Use JUnit wizards in JDeveloper to create test fixtures, cases, and suites. In addition to wizards for creating test components for generic projects, specialized wizards for business components projects are provided.
JUnit is an optional feature that can be installed and integrated with JDeveloper.
After you install JUnit as an extension, additional online documentation is installed. These help topics appear under Help Table of Contents under the folder Creating a JUnit Test for a Java Project.
JUnit is an optional feature that is not distributed with JDeveloper. You must download and install it if you wish to use it.
Note:
JUnit is provided under an IBM public license agreement. You must accept to the license agreement before downloading JUnit.
To install JUnit in JDeveloper:
Use the IDE Update Wizard to download JUnit from the Oracle Technology Network (OTN).
Exit and restart JDeveloper.
JUnit will be installed. Use the Extension Manager if you wish to uninstall it.
A JUnit test application consists of the following components:
One or more test cases, which invoke the methods that are to be tested, and make assertions about the expected results. While test case classes generated by default have 'Test' in their names, the user can specify any valid Java name.
Test fixtures, which provide the state in which the tests are run. Any class can serve as a test fixture, but JDeveloper provides wizards to help you create specialized test fixture classes. While test fixture classes generated by default have 'Fixture' in their names, the user can specify any valid Java name.
A test suite, which invokes the test cases. Default test suite classes have 'AllTests' in their names.
A runner, which invokes the test suite and collates and displays the results of the tests.
A test fixture is a set of objects, having known values, that provide data for the test cases. Any class can serve as a test fixture, but JDeveloper provides wizards to help you create custom test fixture classes and various specialized test fixture classes.
To create a JUnit custom test fixture class:
In the Navigator, select the project.
Choose File > New to open the New Gallery.
In the Categories tree, expand General and select Unit Tests.
In the Items list, double-click Test Fixture.
Complete the wizard to create the test fixture class. The class created by the wizard will be opened for editing.
In the Categories tree, expand General and select Unit Tests (JUnit).
In the Items list, double-click Custom Test Fixture.
Complete the wizard to create the test fixture class. For more information at any time, press F1 or click Help from within the dialog.
In the Categories tree and expand the Unit Tests.
Click Test Suite > OK.
In the Items list, double-click Test Fixture.
Complete the wizard to create the test fixture class. For more information at any time, press F1 or click Help from within the dialog.
The class created by the wizard will be opened for editing.
Modify the file as needed. In particular, to the setUp() method add code that initializes test fixture objects, and to the tearDown() method add code that releases any resources they acquire.
A test fixture is a set of objects, having known values, that provide data for the test cases. A JDBC test fixture provides code that establishes a database connection for the test cases to use.
To create a JUnit JDBC test fixture class:
In the navigator, select the project.
Choose File, then New to open the New Gallery.
In the Categories tree, expand General and select Unit Tests (JUnit).
In the Items list, double-click JDBC Test Fixture.
Complete the dialog to create the test fixture class. For more information at any time, press F1 or click Help from within the dialog.
The class that was created will be opened for editing.
Modify the file as needed. In particular, to the setUp()
method add code that initializes test fixture objects, and to the tearDown()
method add code that releases any resources they acquire.
A test case class has one or more methods that perform tests by calling JUnit assertions. Example 18-8 shows a typical test case in JUnit 3.x. It passes test fixture data to the method being tested, and then compare the result with a known value to confirm that it is what is expected.
Example 18-8 JUnit 3.x Test Case
public void testCountChars() { int expected = 4; int actual = fixture1.countChars('a'); assertEquals(expected, actual); }
Example 18-9 JUnit 4 Test Case
@Test public void testCountChars() { int expected = 4; int actual = fixture1.countChars('a'); Assert.assertEquals(expected, actual); }
In the test case shown in Example 18-9, countChars()
is being tested, and the result of the test is checked by assertEquals()
, which is one of a variety of assertion methods defined in the JUnit Assert class. The state of the test fixture, fixture1
, is established in the setUp()
method, which will have been called before the test case is called, as shown in Example 18-10.
protected void setup() throws Exception { fixture1 = new StringFixture("Goin' to Kansas City, Kansas City, here I come."); }
To create a JUnit test case class:
In the navigator, select the project or the particular class that you want to test.
Choose File, then New to open the New Gallery.
In the Categories tree, expand General and select Unit Tests (JUnit).
In the Items list, double-click Test Case.
Complete the wizard to create the test fixture class. The class created by the wizard will be opened for editing.
A test suite is a class that invokes test cases.
The JUnit Test Suite wizard has options to insert a main() method and a call to a TestRunner class. Within JDeveloper, this will open the JUnit TestRunner log window to display the test results. Edit the method if you wish to use a different test runner.
In the JUnit 3.x test suite shown in Example 18-11, the suite()
method creates a TestSuite instance and adds the test cases to it. Edit this method if you wish to add or remove test cases.
Example 18-11 JUnit 3.x Test Suite
public class AllTests { public static Test suite() { TestSuite suite; suite = new TestSuite("project1.AllTests"); return suite; }
In the JUnit 4 test suite shown in Example 18-12, the test case classes are written with @Suite and @RunWith annotations.
Example 18-12 JUnit 4 Test Suite
@RunWith(Suite.class) @Suite.SuiteClasses( {}) public class AllTests1 { public static void main(String[] args) { String[] args2 = { AllTests1.class.getName() }; org.junit.runner.JUnitCore.main(args2); } }
To create a JUnit test suite class:
In the navigator, select the project.
Choose File, then New to open the New Gallery.
In the Categories tree, expand General and select Unit Tests (JUnit).
In the Items list, double-click Test Suite.
Complete the wizard to create the test fixture class. The class created by the wizard will be opened for editing.
Modify the file as needed. In particular:
In the suite() method add the test cases.
In the main() method replace the runner invocation, if desired.
You can add a unit test for a method to an existing JUnit test case class.
To add a test to a JUnit test case class:
In the code editor, select a method for which you want to create a new unit test.
From the main menu, choose Source > New Method Test. The New Method Test dialog is opened.
Select Add to Existing TestCase Class.
From the Class Name dropdown box, or by using Browse, select the test case class that you want to add the new test to.
To add the new test to the test case, click OK.
You update a test suite with all test cases in a project.
In a class that has a suite() method, from the main menu, choose Source > Refresh Test Suite. The Refresh Test Suite dialog is opened.
Ensure that all items in the list of test cases are checked.
To update the test suite, click OK.