Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Eclipse 2.0 JDT Plug−in Developer Guide Documentation Authored by OTI Documentation produced using PDF Book Toolkit for Java and Eclipse T.J. Watson Research Center, IBM © Copyright IBM Corp. and others 2000, 2002. All Rights Reserved. Java and all Java−related trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S., other countries, or both. License Eclipse.org makes available all content in this document ("Content"). Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the Common Public License Version 1.0 ("CPL"). A copy of the CPL is available at http://www.eclipse.org/legal/cpl−v10.html. For purposes of the CPL, "Program" will mean the Content. JDT Plug−in Developer Guide Table of Contents 1 Programmer's Guide................................................................................................................................................................................1/48 1.1 Java Development Tooling overview......................................................................................................................................1/48 1.1.1 Java elements and resources.................................................................................................................................1/48 1.1.2 JDT Core packages...............................................................................................................................................4/48 1.1.3 JDT user interface..................................................................................................................................................4/48 1.2 Using the JDT API...................................................................................................................................................................5/48 1.2.1 Manipulating Java code........................................................................................................................................5/48 1.2.2 Compiling Java code...........................................................................................................................................10/48 1.2.3 Using the Java search engine..............................................................................................................................11/48 1.2.4 Running a Java program.....................................................................................................................................13/48 1.2.5 Manipulating JDT Core options.........................................................................................................................14/48 1.2.6 Performing CodeAssist on Java code.................................................................................................................17/48 1.2.7 Programmatically launching a Java editor...........................................................................................................19/48 1.2.8 Creating Java specific prompter dialogs..............................................................................................................19/48 1.2.9 How to present Java elements in a standard JFace viewer..................................................................................19/48 1.2.10 Programmatically writing a Jar file...................................................................................................................20/48 1.2.11 How to create a customized 'new Java element' wizard page............................................................................21/48 1.2.12 Manipulating code with a preview in a Java editor...........................................................................................22/48 2 Reference.................................................................................................................................................................................................23/48 2.1 Eclipse JDT API Specification..............................................................................................................................................23/48 2.1.1 Package org.eclipse.jdt.core................................................................................................................................23/48 2.1.2 Package org.eclipse.jdt.core.compiler................................................................................................................25/48 2.1.3 Package org.eclipse.jdt.core.dom.......................................................................................................................26/48 2.1.4 Package org.eclipse.jdt.core.eval........................................................................................................................28/48 2.1.5 Package org.eclipse.jdt.core.jdom......................................................................................................................29/48 2.1.6 Package org.eclipse.jdt.core.search....................................................................................................................29/48 2.1.7 Package org.eclipse.jdt.core.util.........................................................................................................................30/48 2.1.8 Package org.eclipse.jdt.launching.......................................................................................................................31/48 2.1.9 Package org.eclipse.jdt.launching.sourcelookup................................................................................................32/48 2.1.10 Package org.eclipse.jdt.ui.................................................................................................................................32/48 2.1.11 Package org.eclipse.jdt.ui.actions.....................................................................................................................33/48 2.1.12 Package org.eclipse.jdt.ui.jarpackager..............................................................................................................36/48 2.1.13 Package org.eclipse.jdt.ui.text..........................................................................................................................36/48 2.1.14 Package org.eclipse.jdt.ui.text.java.hover.........................................................................................................37/48 2.1.15 Package org.eclipse.jdt.ui.wizards....................................................................................................................37/48 2.1.16 Package org.eclipse.jdt.debug.core...................................................................................................................38/48 2.1.17 Package org.eclipse.jdt.debug.eval...................................................................................................................39/48 2.1.18 Package org.eclipse.jdt.debug.ui.......................................................................................................................39/48 2.1.19 Package org.eclipse.jdt.debug.ui.launchConfigurations...................................................................................39/48 2.2 JDT Extension Points............................................................................................................................................................40/48 2.2.1 Classpath Variable Initializer...............................................................................................................................40/48 2.2.2 Classpath Container Initializer.............................................................................................................................41/48 2.2.3 Code Formatter....................................................................................................................................................41/48 2.2.4 Java Runtime Classpath Entry Resolvers...........................................................................................................41/48 2.2.5 Java Runtime Classpath Providers......................................................................................................................42/48 2.2.6 Java VM Connectors...........................................................................................................................................42/48 2.2.7 Java VM Install Types........................................................................................................................................43/48 2.2.8 VM Install Type UI Page.....................................................................................................................................44/48 2.2.9 Java Element Filters.............................................................................................................................................44/48 2.2.10 Java Editor Text Hovers...................................................................................................................................45/48 2.2.11 Classpath Container Page..................................................................................................................................45/48 2.3 Other Reference Information.................................................................................................................................................46/48 2.3.1 Eclipse Platform Map of Java Development Tooling Plug−ins.........................................................................46/48 3 JDT Questions Index..............................................................................................................................................................................47/48 3.1 JDT Core................................................................................................................................................................................47/48 3.2 JDT UI...................................................................................................................................................................................47/48 08/05/2002 1/48 JDT Plug−in Developer Guide 2/48 08/05/2002 1 Programmer's Guide 1.1 Java Development Tooling overview The Eclipse platform is delivered with a full featured Java integrated development environment (IDE). Java development tooling (JDT) allows users to write, compile, test, debug, and edit programs written in the Java programming language. The JDT makes use of many of the platform extension points and frameworks described in the Platform Plug−in Developer Guide. This guide discusses the extension points and API provided by the JDT. We assume that you already understand the concepts of plug−ins, extension points, workspace resources, and the workbench UI. We first look at how the JDT tools are structured. It's easiest to think of the JDT as a set of plug−ins that add Java specific behavior to the generic platform resource model and contribute Java specific views, editors, and actions to the workbench. Then we will look at how to use the JDT API to accomplish common tasks, such as generating, compiling, and running Java code programmatically. 1.1.1 Java elements and resources The Java model is the set of classes that model the objects associated with creating, editing, and building a Java program. The Java model classes are defined in the org.eclipse.jdt.core.* packages. These classes implement Java specific behavior for resources and further decompose Java resources into model elements. 1.1.1.1 Java elements The package org.eclipse.jdt.core defines the classes that model the elements that compose a Java program. The JDT uses an in−memory object model to represent the structure of a Java program. This model is hierarchical. Elements of a program can be decomposed into child elements. Java elements are a similar resource objects. When you work with a Java element, you are actually working with a handle to some underlying model object. You must use the exists() protocol to determine whether the element is actually present in the workspace. The following table summarizes the different kinds of Java elements. Element IJavaModel IJavaProject Description Represents the root Java element, corresponding to the workspace. The parent of all Java projects. Represents a Java project in the workspace. (Child of IJavaModel ) Represents a set of package fragments, and maps the fragments to an underlying resource which is either a IPackageFragmentRoot folder, JAR, or ZIP file. (Child of IJavaProject ) Represents the portion of the workspace that corresponds to an entire package, or a portion of the package. IPackageFragment (Child of IPackageFragmentRoot ) ICompilationUnit Represents a Java source (.java) file. (Child of IPackageFragment ) IPackageDeclaration Represents a package declaration in a compilation unit. (Child of ICompilationUnit ) IImportContainer Represents the collection of package import declarations in a compilation unit. (Child of ICompilationUnit ) IImportDeclaration Represents a single package import declaration. (Child of IImportContainer ) IType Represents either a source type inside a compilation unit, or a binary type inside a class file. IField Represents a field inside a type. (Child of IType ) IMethod Represents a method or constructor inside a type. (Child of IType ) IInitializer Represents a static or instance initializer inside a type. (Child of IType ) IClassFile Represents a compiled (binary) type. (Child of IPackageFragment ) All Java elements support the IJavaElement interface. Some of the elements are shown in the Packages view. These elements implement the IOpenable interface, since they must be opened before they can be navigated. The figure below shows how these elements are represented in the Packages view. 08/05/2002 1/48 1 Programmer's Guide JDT Plug−in Developer Guide The Java elements that implement IOpenable are mainly created from information found in the underlying resource files. The same elements are represented generically in the resource navigator view. Other elements correspond to the items that make up a Java compilation unit. The figure below shows a Java compilation unit and a content outliner that displays the source elements in the compilation unit. 2/48 08/05/2002 JDT Plug−in Developer Guide 1.1.1 Java elements and resources These elements implement the ISourceReference interface, since they contain corresponding source code. (As these elements are selected in the content outliner, their corresponding source code is shown in the Java editor). 1.1.1.2 Java elements and their resources Many of the Java elements correspond to generic resources in the workspace. When you want to create Java elements from a generic resource the class JavaCore is the best starting point. The following code snippet shows how to get Java elements from their corresponding resources. private void createJavaElementsFrom(IProject myProject, IFolder myFolder, IFile myFile) { IJavaProject myJavaProject = JavaCore.create(myProject); if (myJavaProject == null) // the project is not configured for Java (has no Java nature) return; // get a package fragment or package fragment root IJavaElement myPackageFragment = JavaCore.create(myFolder); // get a .java (compilation unit), .class (class file), or // .jar (package fragment root) IJavaElement myJavaFile = JavaCore.create(myFile); } JavaCore is also used to maintain the Java class path, including locations for finding source code and libraries, and locations for generating output binary (.class) files. When you create a Java project from a simple project, JavaCore will check to see if the project is configured with the Java nature. The JDT plug−in uses a project nature to designate a project as having Java behavior. This nature (org.eclipse.jdt.core.JavaCore#NATURE_ID ) is assigned to a project when the "New Java project" wizard creates a project. If the Java nature is not configured on a project, JavaCore will return null when asked to create the project. What are the unique characteristics of Java projects? They record their classpath in a ".classpath" file and add the Java incremental project builder to the project's build spec. Otherwise, they are just regular projects and can be configured with other natures (and other incremental builders) by plug−ins. Plug−ins that want to configure projects with Java behavior in addition to their own behavior typically use the NewJavaProjectWizardPage to assign the Java nature to the project in addition to their own custom natures or behavior. IJavaModel can be considered the parent of all projects in the workspace that have the Java project nature (and therefore can be treated as an IJavaProject). 08/05/2002 3/48 1.1.2 JDT Core packages JDT Plug−in Developer Guide 1.1.2 JDT Core packages These are the JDT Core packages which give you access to the Java model objects. The following roadmap outlines the major functions of the JDT Core packages: • org.eclipse.jdt.launching provides classes for launching Java runtimes from the platform. JavaRuntime implements static methods to access registered VMs and compute runtime classpaths and source lookup paths. A family of VM's (such as the JDK) is represented by the IVMInstallType class. IVMInstall represents particular installations within a family. The IVMRunner is used to start a particular Java VM and register its processes with the debug plug−in. • org.eclipse.jdt.debug supports a Java debug model based on JDI/JDWP that can be used for controlling a Java program under debug. • org.eclipse.jdt.core.dom supports Abstract Syntax Trees (AST) that can be used for examining the structure of a compilation unit down to the statement level. • org.eclipse.jdt.core.search supports searching the workspace's Java elements that match a particular description. SearchEngine allows you to set up searches in the workspace. You can search for particular patterns inside a Java element. You can also scope the search according to several predefined search types: searching for declarations of the pattern, implementors of the pattern, references to the pattern, or all occurrences of the pattern. • org.eclipse.jdt.core.jdom supports a Java Document Object Model (DOM) that can be used for walking the structure of a Java compilation unit. • org.eclipse.jdt.core.eval supports the evaluation of code snippets in a scrapbook or inside the debugger. 1.1.3 JDT user interface The org.eclipse.jdt.ui plug−in implements the Java specific user interface classes that manipulate Java elements. The following roadmap outlines the major functions in the org.eclipse.jdt.ui package and its subpackages. • org.eclipse.jdt.ui provides support classes for presenting Java elements in the user interface. The class JavaUI is the main access point to the Java user interface components. It allows you to programmatically open editors on Java elements, open a Java or Java Browsing perspective and open package and type prompter dialogs. The package exposes constants for retrieving Java user interface parts from the workbench registry and for retrieving preference settings from the Java preferences. JavaUI gives access to the IWorkingCopyManager . It manages the working copies that are in use for Java compilation units. The interfaces ITypeHierarchyViewPart and IPackagesViewPart define the programming interface that interacts with the type hierarchy and packages view parts. The classes StandardJavaElementContentProvider and JavaElementLabelProvider support the presentation of Java elements in JFace viewers. JavaElementSorter can be plugged into a JFace viewer to sort Java elements according to the Java UI sorting style. The class JavaElementImageDescriptor can be used to create an image based on an arbitrary base image descriptor and a set of flags specifying which Java specific adornments (e.g. static, final, synchronized, ....) are to be superimposed on the image. • org.eclipse.jdt.ui.actions provides actions and action groups to populate tool bars, global menu bars and context menus with JDT specific functionality. It is recommended that clients use action groups to populate menus and tool bars instead of adding actions directly. This shields clients from missing newly added actions or from using outdated menu structures. • org.eclipse.jdt.ui.jarpackager provides classes and interfaces to generate a JAR file. It offers hooks to extend JarPackageData to load and store the JarPackageData and to write the JAR itself. • org.eclipse.jdt.ui.text provides support classes for presenting Java text. The class JavaTextTools provides access to the different scanners to partition and color Java source code. The class JavaSourceViewerConfiguration defines a standard configuration for a Java source viewer. • org.eclipse.jdt.ui.text.java.hover provides implentations for presenting text hovers in Java editors. The interface IJavaEditorTextHover defines the programming interface for a text hover. See extension point org.eclipse.jdt.ui.javaEditorTextHovers for instructions on how to define a new Java text hover. • org.eclipse.jdt.ui.wizards provides wizard pages for creating Java elements. Supported elements are projects, packages, classes and interfaces. The class JavaCapabilityConfigurationPage supports editing the Java build settings (source folder setup, 4/48 08/05/2002 JDT Plug−in Developer Guide 1.2 Using the JDT API referenced projects and, referenced and exported libraries). 1.2 Using the JDT API Given that the JDT supplies a full featured Java IDE, why would you need to use the JDT API? If you are building a plug−in that interacts with Java programs or resources as part of its function, you may need to do one or more of the following things: • Programmatically manipulate Java resources, such as creating projects, generating Java source code, performing builds, or detecting problems in code. • Programmatically launch a Java program from the platform • Provide a new type of VM launcher to support a new family of Java runtimes • Add new functions and extensions to the Java IDE itself If you want to use JDT API in your plug−in, you must include the JDT plug−ins as prerequisites in your plug−in.xml. • org.eclipse.jdt.core is the plug−in that defines the core Java elements and API. You should always list this plug−in as a prerequisite. • org.eclipse.jdt.ui is the plug−in that defines the Java UI API. You should list this plug−in as a prerequisite if you are using the JDT UI classes. • org.eclipse.jdt.launching is the plug−in that defines the Java launching and runtime support. You should list this plug−in as a prerequisite if you need to launch Java virtual machines programmatically. • org.eclipse.jdt.debug is the plug−in that defines the Java debug model. You should list this plug−in as a prerequisite if you need to programmatically access objects in a program being debugged. • org.eclipse.jdt.debug.ui is the plug−in that defines the Java debug UI extensions. You should list this plug−in as a prerequisite if you need to programmatically access the prompting source locator or Java launch configuration tabs. 1.2.1 Manipulating Java code Your plug−in can use the JDT API to create classes or interfaces, add methods to existing types, or alter the methods for types. The simplest way to alter Java objects is to use the Java element API. More general techniques can be used to work with the raw source code for a Java element. 1.2.1.1 Code modification using Java elements 1.2.1.1.1 Generating a compilation unit The easiest way to programmatically generate a compilation unit is to use IPackageFragment.createCompilationUnit. You specify the name and contents of the compilation unit. The compilation unit is created inside the package and the new ICompilationUnit is returned. A compilation unit can be created generically by creating a file resource whose extension is ".java" in the appropriate folder that corresponds to the package directory. Using the generic resource API is a back door to the Java tooling, so the Java model is not updated until the generic resource change listeners are notified and the JDT listeners update the Java model with the new compilation unit. 1.2.1.1.2 Modifying a compilation unit Most simple modifications of Java source can be done using the Java element API. For example, you can query a type from a compilation unit. Once you have the IType, you can use protocols such as createField, createInitializer, createMethod, or createType to add source code members to the type. The source code and information about the location of the member is supplied in these methods. The ISourceManipulation interface defines common source manipulations for Java elements. This includes methods for renaming, moving, copying, or deleting a type's member. 1.2.1.1.3 Working copies Code can be modified by manipulating the compilation unit (and thus the underlying IFile is modified) or one can modify an in−memory copy of the compilation unit called a working copy. A working copy is obtained from a compilation unit using the getWorkingCopy method. Whoever creates such a working copy is responsible for destroying it when not needed any longer using the destroy method. 08/05/2002 5/48 1.2.1 Manipulating Java code JDT Plug−in Developer Guide Working copies modify an in−memory buffer. The getWorkingCopy() method creates a default buffer, but clients can provide their own buffer implementation using the getWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor) method. Clients can manipulate the text of this buffer directly. If they do so, they must synchronize the working copy with the buffer from time to time using either the reconcile() method or the reconcile(boolean,IProgressMonitor) method. Finally a working copy can be saved to disk (replacing the original compilation unit) using the commit method. For example the following code snippet creates a working copy on a compilation unit using a custom buffer factory. The snippet modifies the buffer, reconciles the changes, commits the changes to disk and finally destroys the working copy. // Get original compilation unit ICompilationUnit originalUnit = ...; // Get buffer factory IBufferFactory factory = ...; // Create working copy IWorkingCopy workingCopy = originalUnit.getWorkingCopy(null, factory, null); // Modify buffer and reconcile IBuffer buffer = ((IOpenable)workingCopy).getBuffer(); buffer.append("class X {}"); workingCopy.reconcile(); // Commit changes workingCopy.commit(false, null); // Destroy working copy workingCopy.destroy(); Working copies can also be shared by several clients. A shared working copy is created using the getSharedWorkingCopy method and it can be later retrieved using the findSharedWorkingCopy method. A shared working copy is thus keyed on the original compilation unit and on a buffer factory. The following shows how client 1 creates a shared working copy, client 2 retrieves this working copy, client 1 destroys the working copy, and client 2 trying to retrieve the shared working copy notices it does not exist any longer: // Client 1 2: Get original compilation unit ICompilationUnit originalUnit = ...; // Client 1 2: Get buffer factory IBufferFactory factory = ...; // Client 1: Create shared working copy IWorkingCopy workingCopyForClient1 = originalUnit.getSharedWorkingCopy(null, factory, null); // Client 2: Retrieve shared working copy IWorkingCopy workingCopyForClient2 = originalUnit.findSharedWorkingCopy(factory); // This is the same working copy assert workingCopyForClient1 == workingCopyForClient2; // Client 1: Destroy shared working copy workingCopyForClient1.destroy(); // Client 2: Attempt to retrieve shared working copy and find out it's null workingCopyForClient2 = originalUnit.findSharedWorkingCopy(factory); assert workingCopyForClient2 == null; 1.2.1.2 Code modification using the DOM/AST API There are two ways to create a CompilationUnit. The first one is to use an existing compilation unit. The second is to start from scratch using the factory methods on AST (Abstract Syntax Tree). 1.2.1.2.1 Creating an AST from an existing compilation unit This is achieved with the parse methods on AST: • parseCompilationUnit(char[]) This method should be used if you simply want to create a CompilationUnit without any binding resolution. Only syntax errors are reported using this method. • parseCompilationUnit(char[] source, String unitName, IJavaProject project). This method can be used to create a CompilationUnit from a byte array. If the IJavaProject is specified, the bindings can be resolved. In this case, the name of the compilation unit is used for the binding resolution. • parseCompilationUnit(ICompilationUnit unit, boolean resolveBindings). This method can be used to create a CompilationUnit from an existing ICompilationUnit. 6/48 08/05/2002 JDT Plug−in Developer Guide 1.2.1 Manipulating Java code All these methods will properly set the positions for each node in the resulting tree. The resolution of bindings has to be requested before the creation of the tree. Resolving the bindings is a costly operation and should be done only when necessary. As soon as the tree has been modified, all positions and bindings are lost. 1.2.1.2.2 From scratch It is possible to create a CompilationUnit from scratch using the factory methods on AST. These method names start with new.... The following is an example that creates a HelloWorld class. The first snippet is the generated output: package example; import java.util.*; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello" + " world"); } } The following snippet is the corresponding code that generates the output. AST ast = new AST(); CompilationUnit unit = ast.newCompilationUnit(); PackageDeclaration packageDeclaration = ast.newPackageDeclaration(); packageDeclaration.setName(ast.newSimpleName("example")); unit.setPackage(packageDeclaration); ImportDeclaration importDeclaration = ast.newImportDeclaration(); QualifiedName name = ast.newQualifiedName( ast.newSimpleName("java"), ast.newSimpleName("util")); importDeclaration.setName(name); importDeclaration.setOnDemand(true); unit.imports().add(importDeclaration); TypeDeclaration type = ast.newTypeDeclaration(); type.setInterface(false); type.setModifiers(Modifier.PUBLIC); type.setName(ast.newSimpleName("HelloWorld")); MethodDeclaration methodDeclaration = ast.newMethodDeclaration(); methodDeclaration.setConstructor(false); methodDeclaration.setModifiers(Modifier.PUBLIC | Modifier.STATIC); methodDeclaration.setName(ast.newSimpleName("main")); methodDeclaration.setReturnType(ast.newPrimitiveType(PrimitiveType.VOID)); SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration(); variableDeclaration.setModifiers(Modifier.NONE); variableDeclaration.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("String")))); variableDeclaration.setName(ast.newSimpleName("args")); methodDeclaration.parameters().add(variableDeclaration); org.eclipse.jdt.core.dom.Block block = ast.newBlock(); MethodInvocation methodInvocation = ast.newMethodInvocation(); name = ast.newQualifiedName( ast.newSimpleName("System"), ast.newSimpleName("out")); methodInvocation.setExpression(name); methodInvocation.setName(ast.newSimpleName("println")); InfixExpression infixExpression = ast.newInfixExpression(); infixExpression.setOperator(InfixExpression.Operator.PLUS); StringLiteral literal = ast.newStringLiteral(); literal.setLiteralValue("Hello"); infixExpression.setLeftOperand(literal); literal = ast.newStringLiteral(); literal.setLiteralValue(" world"); infixExpression.setRightOperand(literal); methodInvocation.arguments().add(infixExpression); ExpressionStatement expressionStatement = ast.newExpressionStatement(methodInvocation); block.statements().add(expressionStatement); methodDeclaration.setBody(block); type.bodyDeclarations().add(methodDeclaration); unit.types().add(type); 1.2.1.2.3 Retrieving extra positions The DOM/AST node contains only a pair of positions (the starting position and the length of the node). This is not always sufficient. In order to retrieve intermediate positions, the IScanner API should be used. For example, we have an InstanceofExpression for which we want to know the positions of the instanceof operator. We could write the following method to achieve this: private int[] getOperatorPosition(Expression expression, char[] source) { 08/05/2002 7/48 1.2.1 Manipulating Java code JDT Plug−in Developer Guide if (expression instanceof InstanceofExpression) { IScanner scanner = ToolFactory.createScanner(false, false, false, false); scanner.setSource(source); int start = expression.getStartPosition(); int end = start + expression.getLength(); scanner.resetTo(start, end); int token; try { while ((token = scanner.getNextToken()) != ITerminalSymbols.TokenNameEOF) { switch(token) { case ITerminalSymbols.TokenNameinstanceof: return new int[] {scanner.getCurrentTokenStartPosition(), scanner.getCurr } } } catch (InvalidInputException e) { } } return null; } The IScanner is used to divide the input source into tokens. Each token has a specific value that is defined in the ITerminalSymbols interface. It is fairly simple to iterate and retrieve the right token. We also recommend that you use the scanner if you want to find the position of the super keyword in a SuperMethodInvocation. 1.2.1.3 Generic source code modification Some source code modifications are not provided via the Java element API. A more general way to edit source code (such as changing the source code for existing elements) is accomplished using the compilation unit's raw source code and the Java DOM. These techniques include the following: // get the source for a compilation unit String contents = myCompilationUnit.getBuffer().getContents(); // Create an editable JDOM myJDOM = new DOMFactory(); myDOMCompilationUnit = myJDOM.createCompilationUnit(contents, "MyClass"); // Navigate and edit the compilation unit structure using // JDOM node protocol. ... // Once modififications have been made to all of the nodes // get the source back from the compilation unit DOM node. String newContents = myDOMCompilationUnit.getContents(); // Set this code back into the compilation unit element myCompilationUnit.getBuffer().setContents(newContents); // Save the buffer to the file. myCompilationUnit.save(); This technique can result in problem markers being associated with incorrect line numbers, since the Java elements were not updated directly. The Java element model does not go any finer than methods and fields. The abstract syntax tree used by the compiler is not available as API, so the techniques used by the JDT to parse source into programmatic structures are not currently available as API. 1.2.1.4 Responding to changes in Java elements If your plug−in needs to know about changes to Java elements after the fact, you can register a Java IElementChangedListener with JavaCore. JavaCore.addElementChangedListener(new MyJavaElementChangeReporter()); You can be more specific and specify the type of events you're interested in using addElementChangedListener(IElementChangedListener, int). For example, if you're only interested in listening for events before the builders run: JavaCore.addElementChangedListener(new MyJavaElementChangeReporter(), ElementChangedEvent.PRE_AUTO_BUILD); There are three kinds of events that are supported by JavaCore: • POST_CHANGE: Listeners of this event kind will get notified during the corresponding POST_CHANGE resource change notification. 8/48 08/05/2002 JDT Plug−in Developer Guide 1.2.1 Manipulating Java code • PRE_AUTO_BUILD: Listeners of this event kind will get notified during the corresponding PRE_AUTO_BUILD resource change notification. • POST_RECONCILE: Listeners of this event kind will get notified at the end of a reconcile operation on a working copy (see IWorkingCopy.reconcile()). Java element change listeners are similar conceptually to resource change listeners (described in tracking resource changes). The following snippet implements a Java element change reporter that prints the element deltas to the system console. public class MyJavaElementChangeReporter implements IElementChangedListener { public void elementChanged(ElementChangedEvent event) { IJavaElementDelta delta= event.getDelta(); if (delta != null) { System.out.println("delta received: "); System.out.print(delta); } } } The IJavaElementDelta includes the element that was changed and flags describing the kind of change that occurred. Most of the time the delta tree is rooted at the Java Model level. Clients must then navigate this delta using getAffectedChildren to find out what projects have changed. The following example method traverses a delta and prints the elements that have been added, removed and changed: void traverseAndPrint(IJavaElementDelta delta) { switch (delta.getKind()) { case IJavaElementDelta.ADDED: System.out.println(delta.getElement() + " was added"); break; case IJavaElementDelta.REMOVED: System.out.println(delta.getElement() + " was removed"); break; case IJavaElementDelta.CHANGED: System.out.println(delta.getElement() + " was changed"); if ((delta.getFlags() IJavaElementDelta.F_CHILDREN) != 0) { System.out.println("The change was in its children"); } if ((delta.getFlags() IJavaElementDelta.F_CONTENT) != 0) { System.out.println("The change was in its content"); } /* Others flags can also be checked */ break; } IJavaElementDelta[] children = delta.getAffectedChildren(); for (int i = 0; i <children.length; i++) { traverseAndPrint(children[i]); } } Several kinds of operations can trigger a Java element change notification. Here are some examples: • Creating a resource, e.g. IPackageFragment.createCompilationUnit (the delta indicates the addition of the compilation unit) • Modifying a resource, e.g. ICompilationUnit.html.createType (the delta indicates that the compilation unit has changed and that a type was added as a child of this compilation unit) • Modifying a project's classpath, e.g. IJavaProject.html.setRawClasspath (the delta indicates that package fragment roots have been added to the classpath, removed from the classpath, or reordered on the classpath) • Modifying a classpath variable value, e.g. JavaCore.html.setClasspathVariable (the delta also indicates that package fragment roots have been affected) • Changing the source attachment of a .jar file, e.g. IPackageFragmentRoot.attachSource (the delta indicates that the source was detached then attached) • Reconciling a working copy with its buffer, e.g. IWorkingCopy.reconcile • Modifying an IFile that ends with ".java" and that is on the project's classpath, e.g. using IFile.setContents (the delta indicates that a compilation unit was changed, but no finer−grained information is provided as this was not done through a Java Model operation) As for IResourceDelta the Java element deltas can be batched using an IWorkspaceRunnable. The deltas resulting from several Java Model operations that are run inside a IWorkspaceRunnable are merged and reported at once. For example the following will trigger 2 Java element change events: // Get package IPackageFragment pkg = ...; // Create 2 compilation units 08/05/2002 9/48 1.2.2 Compiling Java code JDT Plug−in Developer Guide ICompilationUnit unitA = pkg.createCompilationUnit("A.java", "public class A {}", false, null); ICompilationUnit unitB = pkg.createCompilationUnit("B.java", "public class B {}", false, null); Whereas the following will trigger 1 Java element change event: // Get package IPackageFragment pkg = ...; // Create 2 compilation units IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.run( new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { ICompilationUnit unitA = pkg.createCompilationUnit("A.java", "public class A {}", false, null); ICompilationUnit unitB = pkg.createCompilationUnit("B.java", "public class B {}", false, null); } }, null); 1.2.2 Compiling Java code The JDT plug−ins include an incremental and batch Java compiler for building Java .class files from source code. There is no direct API provided by the compiler. It is installed as a builder on Java projects. Compilation is triggered using standard platform build mechanisms. The platform build mechanism is described in detail in resource builders . 1.2.2.1 Compiling code You can programmatically compile the Java source files in a project using the build API. IProject myProject; IProgressMonitor myProgressMonitor; myProject.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, myProgressMonitor); For a Java project, this invokes the Java incremental project builder (along with any other incremental project builders that have been added to the project's build spec). The generated .class files are written to the designated output folder. In the case of a full batch build, all the .class files in the output folder are 'scrubbed' to ensure that no stale files are found. Make sure that you place all your .class files, for which you do not have corresponding source files, in separate class file folders on the classpath instead of the output folder. Additional resource files are also copied to the output folder. You can control which resource files are copied using the resource filter. For example, to filter files ending with '.ignore' and folders named 'META−INF', use: Hashtable options = JavaCore.getOptions(); options.put(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, "*.ignore,META−INF/"); JavaCore.setOptions(options); Filenames are filtered if they match one of the supplied patterns. Entire folders are filtered if their name matches one of the supplied folder names which end in a path separator. The incremental and batch builders can also be configured to only generate a single error when the .classpath file has errors. This option is set by default and eliminates numerous errors, all usually caused by a missing jar file. See the CORE_JAVA_BUILD_INVALID_CLASSPATH option of JavaCore . 1.2.2.2 Using the ant javac adapter The Eclipse compiler can be used inside an Ant script using the javac adapter. In order to use the Eclipse compiler, you simply need to define the build.compiler property in your script. Here is a small example. <?xml version="1.0" encoding="UTF−8"?> <project name="compile" default="main" basedir="../."> <property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/> <property name="root" value="${basedir}/src"/> <property name="destdir" value="d:/temp/bin" /> <target name="main"> <javac srcdir="${root}" destdir="${destdir}" debug="on" nowarn="on" extdirs="d:/extdirs" source="1.4"> <classpath> <pathelement location="${basedir}/../org.eclipse.jdt.core/bin"/> </classpath> 10/48 08/05/2002 JDT Plug−in Developer Guide 1.2.2 Compiling Java code </javac> </target> </project> The syntax used for the javac Ant task can be found in the Ant javac task documentation . The current adapter supports the Javac Ant task 1.4.1. A 1.5 version will be available when Ant 1.5 is released. 1.2.2.3 Problem determination JDT Core defines a specialized marker (marker type "org.eclipse.jdt.core.problem ") to denote compilation problems. To programmatically discover problems detected by the compiler, the standard platform marker protocol should be used. See resource markers for an overview of using markers. The following snippet finds all Java problem markers in a compilation unit. public IMarker[] findJavaProblemMarkers(ICompilationUnit cu) throws CoreException { IResource javaSourceFile = cu.getUnderlyingResource(); IMarker[] markers = javaSourceFile.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE); } Java problem markers are maintained by the Java project builder and are removed automatically as problems are resolved and the Java source is recompiled. The problem id value is set by one of the constants in IProblem . The problem's id is reliable, but the message is localized and therefore can be changed according to the default locale. The constants defined in IProblem are self−descriptive. An implementation of IProblemRequestor should be defined to collect the problems discovered during a Java operation. Working copies can be reconciled with problem detection if a IProblemRequestor has been supplied for the working copy creation. To achieve this, you can use the reconcile method. Here is an example: ICompilationUnit unit = ..; // get some compilation unit // create requestor for accumulating discovered problems IProblemRequestor problemRequestor = new IProblemRequestor() { public void acceptProblem(IProblem problem) { System.out.println(problem.getID() + ": " + problem.getMessage()); } public void beginReporting() {} public void endReporting() {} public boolean isActive() { return true; } // will detect problems if active }; // use working copy to hold source with error IWorkingCopy workingCopy = (IWorkingCopy)unit.getWorkingCopy(null, null, problemRequestor); ((IOpenable)workingCopy).getBuffer().setContents("public class X extends Zork {}"); // trigger reconciliation workingCopy.reconcile(true, null); You can add an action on the reported problems in the acceptProblem(IProblem) method. In this example, the reported problem will be that Zork cannot be resolved or is not a valid superclass and its id is IProblem.SuperclassNotFound . 1.2.3 Using the Java search engine Your plug−in can use the JDT API to search Java projects in the workspace for Java elements, such as method references, field declarations, implementors of an interface, etc. The entry point for Java search is the SearchEngine class. Factory methods on this class, such as createSearchPattern (creates a search pattern) or createJavaSearchScope (creates a Java search scope) are used by the search method. This method reports results to an IJavaSearchResultCollector which you must implement. 1.2.3.1 Preparing for search A search operation will use both a pattern for describing the nature of the search, and a scope for restraining the range of investigation. 08/05/2002 11/48 1.2.3 Using the Java search engine JDT Plug−in Developer Guide 1.2.3.1.1 Creating a Java search pattern A search pattern defines how search results are found. You can either create a search pattern from a Java element (see createSearchPattern(IJavaElement, int)) or from a string (see createSearchPattern(String, int, int, boolean).) The last method supports wildcards (i.e. '*') and can be used to widen the search results. For example, creating a search pattern for searching for references to a given method is done as follows: // Get the method IMethod method = ...; // Create search pattern ISearchPattern pattern = SearchEngine.createSearchPattern(method, IJavaSearchConstants.REFERENCES); Or creating a search pattern for searching for declarations of all types starting with "Obj": // Create search pattern ISearchPattern pattern = SearchEngine.createSearchPattern("Obj*", IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATION The following search patterns are supported: • Package declarations • Type declarations • Field declarations • Method (and constructor) declarations • Package references • Type references • Interface implementors • Field references • Field write accesses • Field read accesses • Method (and constructor) references • Combinations of the above patterns using the OR pattern (see createOrSearchPattern) 1.2.3.1.2 Creating a Java search scope If you are interested in search results in a given project or even in a given package, or if you know that search results can be only in a hierarchy of a given type, you can create the appropriate search scope using createJavaSearchScope(IJavaElement[]) or createHierarchyScope(IType). For example, creating a search scope on a given package is done as follows: // Get the package IPackageFragment pkg = ...; // Create search scope IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {pkg}); Or creating a search scope on the hierarchy of a given type is: // Get the type IType type = ...; // Create search scope IJavaSearchScope scope = SearchEngine.createHierarchyScope(type); Finally, you can create a search scope on the entire workspace: // Create search scope IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); 1.2.3.2 Searching Once you have created a search pattern and a search scope, and you have implemented IJavaSearchResultCollector, you can start a search query as follows: // Get the search pattern ISearchPattern pattern = ...; // Get the search scope IJavaSearchScope scope = ...; // Get the search result collector 12/48 08/05/2002 JDT Plug−in Developer Guide 1.2.3 Using the Java search engine IJavaSearchResultCollector collector = ...; // Search SearchEngine searchEngine = new SearchEngine(); searchEngine.search(ResourcesPlugin.getWorkspace(), pattern, scope, collector); A notification that the search starts is sent to your search result collector using the aboutToStart method. Then, each search result is reported using the accept method. Finally done indicates that the search has ended. 1.2.3.3 Collecting search results Search results are reported using the accept method. Paragraphs below detail each argument to this method. 1.2.3.3.1 Resources and Java elements A search result can correspond to a Java element (e.g. a type declaration) or it can be contained in a Java element (e.g. a reference to a type inside a method). The search engine always tries to find the innermost Java element that corresponds to or that contains the search result. For example, searching for type declarations by name could find a local type declaration. Since the Java model doesn't represent local types, the method that contains this local type declaration is given to the result collector. The search engine also tries to give the resource that contains the Java element to the result collector. So if the Java element is a method in a compilation unit, the resource is the corresponding IFile. If the element is contained in a .jar file, the resource is the .jar file, if this .jar file is in the workspace. If it is an external .jar file, then the resource is null. 1.2.3.3.2 Source positions Source positions are given relative to the compilation unit that contains the search result. If the search result is contained in a .jar file, the source positions are relative to the attached source. They are (−1, −1) if there is no source attached to the .jar file. 1.2.3.3.3 Accurate versus inaccurate search results In most cases search results are accurate, meaning that the search engine was able to determine that the given match is what was asked for. However in some cases the search engine is unable to do so, in such cases the match is inaccurate. Some possible reasons why a match could be inaccurate are: • The classpath on the project that contains the result is not properly set. For example, it refers to a project that is not accesible, a jar on the classpath requires another jar that is not on the classpath, etc. • The user code would not compile. For example, it refers to a class that is not yet defined. 1.2.4 Running a Java program The JDT API includes facilities for launching a Java program using the VM install that is currently configured by the user for a Java project. 1.2.4.1 Launching a compiled Java program Java programs that have been compiled in a Java project can be run by getting the appropriate IVMRunner for the Java project and running the class by name. The following code snippet shows how the class MyClass inside myJavaProject can be launched. IVMInstall vmInstall = JavaRuntime.getVMInstall(myJavaProject); if (vmInstall == null) vmInstall = JavaRuntime.getDefaultVMInstall(); if (vmInstall != null) { IVMRunner vmRunner = vmInstall.getVMRunner(ILaunchManager.RUN_MODE); if (vmRunner != null) { String[] classPath = null; try { classPath = JavaRuntime.computeDefaultRuntimeClassPath(myJavaProject); } catch (CoreException e) { } if (classPath != null) { VMRunnerConfiguration vmConfig = new VMRunnerConfiguration("MyClass", classPath); ILaunch launch = new Launch(null, ILaunchManager.RUN_MODE, null); vmRunner.run(vmConfig, launch, null); } } } Another way to launch a Java program is to create a Java application launch configuration, and launch it. The following snippet shows how the class MyClass inside myJavaProject can be launched using a simple launch configuration. By default, the resulting running 08/05/2002 13/48 1.2.5 Manipulating JDT Core options JDT Plug−in Developer Guide application uses the JRE and classpath associated with myJavaProject. ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = manager.getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION); ILaunchConfigurationWorkingCopy wc = type.newInstance(null, "SampleConfig"); wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "myJavaProject"); wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, "myClass"); ILaunchConfiguration config = wc.doSave(); config.launch(ILaunchManager.RUN_MODE, null); 1.2.5 Manipulating JDT Core options JDT Core options are accessible from a few APIs. All of these APIs are located in JavaCore. Only four methods are necessary to manipulate the options: • JavaCore.getDefaultOptions() − Answers the default value of the options. • JavaCore.getOption(String optionName) − Answers the value of a specific option. • JavaCore.getOptions() − Answers the current values of the options. • JavaCore.setOptions(Hashtable newOptions) − Replaces the options values by new values. The options are manipulated as a hashtable of all known configurable options with their values. Helper constants have been defined on JavaCore for each option ID and its possible constant values. If you want to configure JDT Core with only your options, the following code fragment would work: // Get the current options Hashtable options = JavaCore.getDefaultOptions(); // Change the value of an option options.put(JavaCore.COMPILER_PB_DEPRECATION, JavaCore.ERROR); // Set the new options JavaCore.setOptions(options); If you want to keep the current options and modify only one of them: // Get the current options Hashtable options = JavaCore.getOptions(); // Change the value of an option options.put(JavaCore.COMPILER_PB_DEPRECATION, JavaCore.ERROR); // Set the new options JavaCore.setOptions(options); 1.2.5.1 JDT Core options descriptions The list of all the JDT Core options are in the following tables. All of the tables have the same organisation with the option id surrounded with parenthesis and the default value printed in bold italics. 1.2.5.1.1 Options category • Compiler options • Builder options • JavaCore options • Formatter options • CodeAssist options 1.2.5.1.2 Compiler options Description Values Generating Local Variable Debug Attribute (COMPILER_LOCAL_VARIABLE_ATTR) When generated, this attribute will enable local variable names to be displayed in the GENERATE debugger, only in places where variables are definitely assigned (.class file is then DO_NOT_GENERATE bigger) Generating Line Number Debug Attribute (COMPILER_LINE_NUMBER_ATTR) When generated, this attribute will enable source code highlighting in the debugger (.class file is then bigger). 14/48 GENERATE DO_NOT_GENERATE 08/05/2002 JDT Plug−in Developer Guide 1.2.5 Manipulating JDT Core options Generating Source Debug Attribute (COMPILER_SOURCE_FILE_ATTR) When generated, this attribute will enable the debugger to present the corresponding source code. GENERATE DO_NOT_GENERATE Preserving Unused Local Variables (COMPILER_CODEGEN_UNUSED_LOCAL) Unless requested to preserve unused local variables (i.e. never read), the compiler will optimize them out, potentially altering debugging. PRESERVE OPTIMIZE_OUT Defining Target Java Platform (COMPILER_CODEGEN_TARGET_PLATFORM) For binary compatibility reason, .class files can be tagged with certain VM versions and later. Note that the "1.4" target requires you to toggle the compliance mode to "1.4" also. VERSION_1_1 VERSION_1_2 VERSION_1_3 VERSION_1_4 Reporting Unreachable Code (COMPILER_PB_UNREACHABLE_CODE) Unreachable code can optionally be reported as an error, warning or simply ignored. The bytecode generation will always optimize it out. ERROR WARNING IGNORE Reporting Invalid Import (COMPILER_PB_INVALID_IMPORT) An import statement that cannot be resolved might optionally be reported as an error, ERROR as a warning or ignored. WARNING IGNORE Reporting Attempt to Override Package−Default Method (COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD) A package default method is not visible in a different package, and thus cannot be overridden. When enabling this option, the compiler will signal such scenarii either as an error or a warning. ERROR WARNING IGNORE Reporting Method With Constructor Name (COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME) Naming a method with a constructor name is generally considered poor style programming. When enabling this option, the compiler will signal such scenarii either as an error or a warning. ERROR WARNING IGNORE Reporting Deprecation (COMPILER_PB_DEPRECATION) When enabled, the compiler will signal use of deprecated API either as an error or a warning. ERROR WARNING IGNORE Reporting Hidden Catch Block (COMPILER_PB_HIDDEN_CATCH_BLOCK) Local to a try statement, some catch blocks may hide others , e.g. try { throw new java.io.CharConversionException(); } catch (java.io.CharConversionException e) { } catch (java.io.IOException e) {}. ERROR WARNING IGNORE When enabling this option, the compiler will issue an error or a warning for hidden catch blocks corresponding to checked exceptions Reporting Unused Local (COMPILER_PB_UNUSED_LOCAL) When enabled, the compiler will issue an error or a warning for unused local variables (i.e. variables never read from) ERROR WARNING IGNORE Reporting Unused Parameter (COMPILER_PB_UNUSED_PARAMETER) 08/05/2002 15/48 1.2.5 Manipulating JDT Core options JDT Plug−in Developer Guide When enabled, the compiler will issue an error or a warning for unused method parameters (i.e. parameters never read from) ERROR WARNING IGNORE Reporting Unused Import (COMPILER_PB_UNUSED_IMPORT) When enabled, the compiler will issue an error or a warning for unused import reference ERROR WARNING IGNORE Reporting Synthetic Access Emulation (COMPILER_PB_SYNTHETIC_ACCESS_EMULATION) When enabled, the compiler will issue an error or a warning whenever it emulates access to a non−accessible member of an enclosing type. Such access can have performance implications. ERROR WARNING IGNORE Reporting Non−Externalized String Literal (COMPILER_PB_NON_NLS_STRING_LITERAL) When enabled, the compiler will issue an error or a warning for non externalized String literal (i.e. non tagged with //$NON−NLS−$) ERROR WARNING IGNORE Reporting Usage of 'assert' Identifier (COMPILER_PB_ASSERT_IDENTIFIER) When enabled, the compiler will issue an error or a warning whenever 'assert' is used ERROR as an identifier (reserved keyword in 1.4) WARNING IGNORE Setting Source Compatibility Mode (COMPILER_SOURCE) Specify whether source is 1.3 or 1.4 compatible. From 1.4 on, 'assert' is a keyword reserved for assertion support. Also note, than when toggling to 1.4 mode, the target VM level should be set to "1.4" and the compliance mode should be "1.4". VERSION_1_3 VERSION_1_4 Setting Compliance Level (COMPILER_COMPLIANCE) Select the compliance level for the compiler. In "1.3" mode, source and target settings should not go beyond "1.3" level. VERSION_1_3 VERSION_1_4 Maximum number of problems reported per compilation unit (COMPILER_PB_MAX_PER_UNIT) Specify the maximum number of problems reported on each compilation unit (if the maximum is zero then all problems are reported). a positive integer. Default value is 100 1.2.5.1.3 Builder options Description Values Specifying Filters for Resource Copying Control (CORE_JAVA_BUILD_RESOURCE_COPY_FILTER) Specify filters to control the resource copy process. (<name> is a file name pattern (only * wild−cards allowed) or the name of a folder which ends with '/') {<name>[,<name>]*}. Default value is "" Abort if Invalid Classpath (CORE_JAVA_BUILD_INVALID_CLASSPATH) Instruct the builder to abort if the classpath is invalid ABORT IGNORE 1.2.5.1.4 JavaCore options Description Values Computing Project Build Order (CORE_JAVA_BUILD_ORDER) Indicate whether JavaCore should enforce the project build order to be based on the classpath prerequisite chain. When requesting to compute, this takes over the platform default order (based on project references). COMPUTE IGNORE Specify Default Source Encoding Format (CORE_ENCODING) 16/48 08/05/2002 JDT Plug−in Developer Guide 1.2.5 Manipulating JDT Core options Get the encoding format for compiled sources. This setting is read−only, it is equivalent to ResourcesPlugin.getEncoding(). any of the supported encoding name. Default value is platform default 1.2.5.1.5 Formatter options Description Values Inserting New Line Before Opening Brace (FORMATTER_NEWLINE_OPENING_BRACE) When Insert, a new line is inserted before an opening brace, otherwise nothing is inserted INSERT DO_NOT_INSERT Inserting New Line Inside Control Statement (FORMATTER_NEWLINE_CONTROL) When Insert, a new line is inserted between } and following else, catch, finally INSERT DO_NOT_INSERT Clearing Blank Lines (FORMATTER_CLEAR_BLANK_LINES) When Clear all, all blank lines are removed. When Preserve one, only one is kept and all others removed. CLEAR_ALL PRESERVE_ONE Inserting New Line Between Else/If (FORMATTER_NEWLINE_ELSE_IF) When Insert, a blank line is inserted between an else and an if when INSERT they are contiguous. When choosing to not insert, else−if will be DO_NOT_INSERT kept on the same line when possible. Inserting New Line In Empty Block (FORMATTER_NEWLINE_EMPTY_BLOCK) When insert, a line break is inserted between contiguous { and }, if } is not followed by a keyword. INSERT DO_NOT_INSERT Splitting Lines Exceeding Length (FORMATTER_LINE_SPLIT) Enable splitting of long lines (exceeding the configurable length). Length of 0 will disable line splitting a positive integer. Default value is 80 Compacting Assignment (FORMATTER_COMPACT_ASSIGNMENT) Assignments can be formatted asymmetrically, e.g. 'int x= 2;', when COMPACT Normal, a space is inserted before the assignment operator NORMAL Defining Indentation Character (FORMATTER_TAB_CHAR) Either choose to indent with tab characters or spaces TAB SPACE Defining Space Indentation Length (FORMATTER_TAB_SIZE) When using spaces, set the amount of space characters to use for each indentation mark. a positive integer. Default value is 4 1.2.5.1.6 CodeAssist options Description Values Activate Visibility Sensitive Completion (CODEASSIST_VISIBILITY_CHECK) When active, completion doesn't show that you can not see (e.g. you can not see private methods of a super class). ENABLED DISABLED Automatic Qualification of Implicit Members (CODEASSIST_IMPLICIT_QUALIFICATION) When active, completion automatically qualifies completion on implicit field references and message expressions. ENABLED DISABLED 1.2.6 Performing CodeAssist on Java code JDT API allows other plugins to perform codeassist or codeselect on some Java elements. Elements that allow this manipulation implement ICodeAssist. In the Java model there are two elements that implement this interface: IClassFile and ICompilationUnit. 08/05/2002 17/48 1.2.6 Performing CodeAssist on Java code JDT Plug−in Developer Guide There are two kinds of manipulation: • Code completion − compute the completion of a Java token. • Code selection − answer the Java element at a given position. Note: completion and selection answer results for a classfile only if it has attached source. 1.2.6.1 Code completion 1.2.6.1.1 Performing a code completion The only way to programmatically perform code completion is to use ICodeAssist.codeComplete. You specify the location of the completion in the unit and provide an instance of ICompletionRequestor to accept the possible completions. Each kind of proposal is accepted by a method of the requestor. The parameters of these methods describe the element (name, parameters, declaring type, ...) and its position, as well as the relevance of the proposal in the current context. When you are not interested by all the result kinds, a simple way to perform code completion is to use CompletionRequestorAdapter. // Get the compilation unit ICompilationUnit unit = ...; // Get the offset int offset = ...; // Create the requestor ICompletionRequestor requestor = new CompletionRequestorAdapter() { public void acceptClass( char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { System.out.println("propose a class named " + new String(className)); } }; // Compute proposals unit.codeComplete(offset, requestor); 1.2.6.1.2 Code completion options The options of code completion can be changed by other plugins. You can modify JDT Core options to change the completion behavior. There are two options: • Activate Visibility Sensitive Completion: when active, completion doesn't answer what you can not see (e.g. you can not see private methods of a super class). • Automatic Qualification of Implicit Members: when active, completion automatically qualifies completion on implicit field references and message expressions. To know how to modify JDT Core options see: What are the JDT Core options? 1.2.6.2 Code selection 1.2.6.2.1 Performing a code selection If you want to programmatically perform code selection, the method to use is ICodeAssist.codeSelect. This method needs to know the start location of the selection and the length. The result is an array of Java elements. Most of the time there is only one element in the array, but if the selection is ambiguous then all the possible elements are returned. // Get the compilation unit ICompilationUnit unit = ...; // Get the offset and length int offset = ...; int length = ...; // perform selection IJavaElement[] elements = unit.codeSelect(offset, length); System.out.println("the selected element is " + element[0].getElementName()); 18/48 08/05/2002 JDT Plug−in Developer Guide 1.2.6 Performing CodeAssist on Java code 1.2.6.2.2 Selection at cursor location. If the length of the selection equals 0 then the selection is computed with the complete enclosing token. public void fooMethod(Object) { } When the offset is after the first character of fooMethod and the length is 0 then the selection is fooMethod. But if the length is 5 then the selection is ooMet. 1.2.7 Programmatically launching a Java editor The JDT UI plug−in provides a utility class, JavaUI, which allows you to programmatically invoke the JDT user interface. The following snippet causes a Java editor to show a specific member of a Java compilation unit. void showMethod(IMember member) { ICompilationUnit cu = member.getCompilationUnit(); IEditorPart javaEditor = JavaUI.openInEditor(cu); JavaUI.revealInEditor(javaEditor, member); } The methods openInEditor and revealInEditor also work for class files and for members contained in class files. 1.2.8 Creating Java specific prompter dialogs The JDT UI plug−in provides the utility class JavaUI, which allows you to programmatically invoke the JDT user interface. The following snippet causes a type prompter dialog to open: public IType selectType() throws JavaModelException { SelectionDialog dialog= JavaUI.createTypeDialog(parent, new ProgressMonitorDialog(parent), SearchEngine.createWorkspaceScope(), IJavaElementSearchConstants.CONSIDER_TYPES, false); dialog.setTitle("My Dialog Title"); dialog.setMessage("My Dialog Message"); if (dialog.open() == IDialogConstants.CANCEL_ID) return null; Object[] types= dialog.getResult(); if (types == null || types.length == 0) return null; return (IType)types[0]; } In addition to methods for creating a type prompter dialog the class JavaUI provides additional methods for creating package and main type prompter dialogs as well. 1.2.9 How to present Java elements in a standard JFace viewer The JDT−UI API provides several classes to present the Java model or parts of it in a standard JFace viewer. This functionality is provided primarily by: • StandardJavaElementContentProvider which translates the Java element hierarchy into a data structure accessible by a tree, table or list viewer • JavaElementLabelProvider which provides corresponding images and labels for a standard JFace viewer Putting the pieces together is quite simple: 08/05/2002 19/48 1.2.9 How to present Java elements in a standard JFace viewer JDT Plug−in Developer Guide ... IJavaProject jProject= ...; TreeViewer viewer= new TreeViewer(parent); // Provide members of a compilation unit or class file, but no working copy elements ITreeContentProvider contentProvider= new StandardJavaElementContentProvider(true, false); viewer.setContentProvider(contentProvider); // There are more flags defined in class JavaElementLabelProvider ILabelProvider labelProvider= new JavaElementLabelProvider( JavaElementLabelProvider.SHOW_DEFAULT | JavaElementLabelProvider.SHOW_QUALIFIED | JavaElementLabelProvider.SHOW_ROOT); viewer.setLabelProvider(labelProvider); // Using the Java model as the viewers input present Java projects on the first level. viewer.setInput(JavaCore.create(ResourcesPlugin.getWorkspace().getRoot())); ... In addition to the Java model the StandardJavaElementContentProvider class supports the following input element types: IJavaProject, IPackageFragmentRoot, IPackageFragment and IFolder. 1.2.9.1 Adding problem and override decorators When a viewer is supposed to include problem annotations, then a DecoratingLabelProvider together with the ProblemsLabelDecorator is used. Below is a code snippet that outlines the use of a problem label decorator: ... DecoratingLabelProvider decorator= new DecoratingLabelProvider(labelProvider, new ProblemsLabelDecorator()); viewer.setLabelProvider(decorator); ... In the same way the OverrideIndicatorLabelDecorator can be used to decorate a normal label provider to show the implement and override indicators for methods. 1.2.9.2 Updating the presentation on model changes Neither the OverrideIndicatorLabelDecorator nor the ProblemsLabelDecorator listen to model changes. Hence, the viewer doesn't update its presentation if the Java or resource marker model changes. The reason for pushing the update onto the client for these classes is that there isn't yet a generic implementation that fulfills all performance concerns. Handling Java model delta inspection and viewer refreshing in each label decorator or provider would lead to multiple delta inspections and unnecessary viewer updates. So what does the client need to do in order to update their viewers ? • OverrideIndicatorLabelDecorator: the client must listen to Java model changes (see JavaCore.addElementChangedListener ) and decide if the change(s) described by the delta invalidates the override indicator of elements presented in the viewer. If so, the class inspecting the delta should trigger a repaint of the corresponding Java elements using the standard JFace viewer API (see update methods on StructuredViewer). • ProblemsLabelDecorator: the client should listen to changes notified by the decorator via a ProblemsLabelChangedEvent (see also ProblemsLabelDecorator.addListener ). Since the marker model is resource based, the listener has to map the resource notifications to its underlying data model. For an example showing how to do this for viewers presenting Java elements see the internal classes ProblemTreeViewer.handleLabelProviderChanged. For the same reasons enumerated for label decorators the StandardJavaElementContentProvider doesn't listen to model changes. If the viewer needs to update its presentation according to Java model changes, then the client should add a corresponding listener to JavaCore. If the change described by the delta invalidates the structure of the elements presented in the viewer then the client should update the viewer using the standard JFace API (see refresh methods on StructuredViewer, and the add and remove methods on TableViewer and AbstractTreeViewer). 1.2.10 Programmatically writing a Jar file The org.eclipse.ui.jarpackager package provides utility classes to programmatically export files to a Jar file. Below is a code snippet that outlines the use of the JarPackageData class: void createJar(IType mainType, IFile[] filestoExport) { Shell parentShell= ...; JarPackageData description= new JarPackageData(); IPath location= new Path("C:/tmp/myjar.jar"); description.setJarLocation(location); description.setSaveManifest(true); 20/48 08/05/2002 JDT Plug−in Developer Guide 1.2.11 How to create a customized 'new Java element' wizard pag description.setManifestMainClass(mainType); description.setElements(filestoExport); IJarExportRunnable runnable= description.createJarExportRunnable(parentShell); try { new ProgressMonitorDialog(parentShell).run(true, true, runnable); } catch (InvocationTargetException e) { // An error has occurred while executing the operation } catch (InterruptedException e) { // operation had been canceled. } } Additional API is provided to create a plug−in specific subclass of JarPackageData. This allows other plug−ins to implement their own Jar export/import wizards and to save the content of the JarPackageData object to a corresponding Jar description file. 1.2.11 How to create a customized 'new Java element' wizard page The org.eclipse.jdt.ui.wizards package provides wizard pages for creating Java elements. Besides using the prefabricated pages clients have the ability to subclass the wizard pages to add their own input fields or to influence the code generation. Below is a sample of a new type wizard page that is customized to create JUnit test case classes. The page initializes the super class field with "junit.framework.TestCase" and adds a checkbox that controls whether method stubs for the setUp() and tearDown() method are to be created. public class TestCaseWizardPage extends NewTypeWizardPage { private Button fCreateStubs; public TestCaseWizardPage() { super(true, "TestCaseWizardPage"); } /** * The wizard managing this wizard page must call this method * during initialization with a corresponding selection. */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); initTypePage(jelem); // define the components for which a status is desired IStatus[] status= new IStatus[] { fContainerStatus, isEnclosingTypeSelected() ? fEnclosingTypeStatus : fPackageStatus, fTypeNameStatus, }; updateStatus(status); } public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 4; GridLayout layout= new GridLayout(); layout.numColumns= nColumns; composite.setLayout(layout); // Create the standard input fields createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); createSeparator(composite, nColumns); createTypeNameControls(composite, nColumns); createSuperClassControls(composite, nColumns); // Create the checkbox controlling whether we want stubs fCreateStubs= new Button(composite, SWT.CHECK); fCreateStubs.setText("Add 'setUp()' and 'tearDown()' to new class"); GridData gd= new GridData(); gd.horizontalSpan= nColumns; fCreateStubs.setLayoutData(gd); setControl(composite); // Initialize the super type field and mark it as read−only setSuperClass("junit.framework.TestCase", false); } 08/05/2002 21/48 1.2.12 Manipulating code with a preview in a Java editor JDT Plug−in Developer Guide protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException { if (fCreateStubs.getSelection()) { String setUpMathod= "public void setUp() {}"; newType.createMethod(setUpMathod, null, false, null); String tearDownMathod= "public void setUp() {}" newType.createMethod(tearDownMathod, null, false, null); } } } 1.2.12 Manipulating code with a preview in a Java editor The JDT Core plugin provides several mechanisms to programmatically create, delete and modify Java elements. See manipulating Java code for an introducation to the API provided by JDT Core. In a UI world it is often useful to have the user confirm a preview before changes are saved. This can be achieved by opening a Java editor on the compilation unit to be modified. The user can then either save the Java editor's content to disk or revert it back to its original content. Below is a code snippet that opens a compilation unit in an editor and then uses the working copy created by the editor to perform the changes: void modifyCompilationUnit(ICompilationUnit cunit) throws PartInitException, CoreException { IEditorPart editor= JavaUI.openInEditor(cunit); IEditorInput input= editor.getEditorInput(); IWorkingCopyManager manager= JavaUI.getWorkingCopyManager(); manager.connect(input); try { ICompilationUnit workingCopy= manager.getWorkingCopy(input); // do the modifications on workingCopy using the normal JDT Core API. } finally { manager.disconnect(input); } // either keep the editor dirty or use editor.doSave(IProgressMonitor monitor) // to save the changes programmatically. } 22/48 08/05/2002 2 Reference 2.1 Eclipse JDT API Specification Java Development Tools Core Plug−in Packages org.eclipse.jdt.core The Java model is the set of classes that model the objects associated with creating, editing, and building a Java program. org.eclipse.jdt.core.compiler This package contains compiler associated infrastructure APIs. org.eclipse.jdt.core.dom The Java DOM is the set of classes that model Java program as a structured document. org.eclipse.jdt.core.eval Provides support for the evaluation of code snippets in a scrapbook or inside the debugger. org.eclipse.jdt.core.jdom Provides a support for java document manipulation through the JDOM model. org.eclipse.jdt.core.search Provides support for searching the workspace Java elements that match a particular description. org.eclipse.jdt.core.util Provides a set of tools and utilities for manipulating .class files and Java model elements. Java Development Tools UI Plug−in Packages org.eclipse.jdt.ui Application programming interfaces for interaction with the Eclipse Java User Interface. org.eclipse.jdt.ui.actions Application programming interfaces for Eclipse Java User Interface specific actions. org.eclipse.jdt.ui.jarpackager Provides classes and interfaces to generate a JAR file. org.eclipse.jdt.ui.text Application programming interfaces for interaction with the Eclipse Java User Interface text support. org.eclipse.jdt.ui.text.java.hover Application programming interfaces for interaction with the Eclipse Java Editor. org.eclipse.jdt.ui.wizards Application programming interfaces for interaction with the Eclipse Java User Interface wizards. Other Packages org.eclipse.jdt.debug.core org.eclipse.jdt.debug.eval org.eclipse.jdt.debug.ui Provides an implementation of a source locator for the Java debug model. org.eclipse.jdt.debug.ui.launchConfigurations Provides an implementation launch configuration tabs for local and remote Java applications. org.eclipse.jdt.launching Application programming interfaces for interaction with the Eclipse Java launching support. org.eclipse.jdt.launching.sourcelookup Application programming interfaces and classes for Eclipse Java source lookup. 2.1.1 Package org.eclipse.jdt.core The Java model is the set of classes that model the objects associated with creating, editing, and building a Java program. See: Description Interface Summary IBuffer A buffer contains the text contents of a resource. IBufferChangedListener A listener, which gets notified when the contents of a specific buffer have changed, or when the buffer is closed. IBufferFactory A factory that creates IBuffers for openables. 08/05/2002 23/48 2 Reference JDT Plug−in Developer Guide IClassFile Represents an entire binary type (single .class file). IClasspathContainer Interface of a classpath container. IClasspathEntry An entry on a Java project classpath identifying one or more package fragment roots. ICodeAssist Common protocol for Java elements that support source code assist and code resolve. ICodeCompletionRequestor Deprecated. Use an ICompletionRequestor instead ICodeFormatter Specification for a generic source code formatter. ICompilationUnit Represents an entire Java compilation unit (.java source file). ICompletionRequestor A completion requestor accepts results as they are computed and is aware of source positions to complete the various different results. ICorrectionRequestor A callback interface for receiving java problem correction. IElementChangedListener An element changed listener receives notification of changes to Java elements maintained by the Java model. IField Represents a field declared in a type. IImportContainer Represents an import container is a child of a Java compilation unit that contains all (and only) the import declarations. IImportDeclaration Represents an import declaration in Java compilation unit. IInitializer Represents a stand−alone instance or class (static) initializer in a type. IJavaElement Common protocol for all elements provided by the Java model. IJavaElementDelta A Java element delta describes changes in Java element between two discrete points in time. IJavaModel Represent the root Java element corresponding to the workspace. IJavaModelMarker Markers used by the Java model. IJavaModelStatus Represents the outcome of an Java model operation. IJavaModelStatusConstants Status codes used with Java model status objects. IJavaProject A Java project represents a view of a project resource in terms of Java elements such as package fragments, types, methods and fields. IMember Common protocol for Java elements that can be members of types. IMethod Represents a method (or constructor) declared in a type. IOpenable Common protocol for Java elements that must be opened before they can be navigated or modified. IPackageDeclaration Represents a package declaration in Java compilation unit. IPackageFragment A package fragment is a portion of the workspace corresponding to an entire package, or to a portion thereof. IPackageFragmentRoot A package fragment root contains a set of package fragments. IParent Common protocol for Java elements that contain other Java elements. IProblemRequestor A callback interface for receiving java problem as they are discovered by some Java operation. IRegion A Java model region describes a hierarchical set of elements. ISourceManipulation Common protocol for Java elements that support source code manipulations such as copy, move, rename, and delete. ISourceRange A source range defines an element's source coordinates relative to its source buffer. ISourceReference Common protocol for Java elements that have associated source code. IType Represents either a source type in a compilation unit (either a top−level type or a member type) or a binary type in a class file. ITypeHierarchy A type hierarchy provides navigations between a type and its resolved supertypes and subtypes for a specific type or for all types within a region. ITypeHierarchyChangedListener A listener which gets notified when a particular type hierarchy object changes. IWorkingCopy 24/48 Common protocol for Java elements that support working copies. 08/05/2002 JDT Plug−in Developer Guide 2.1.1 Package org.eclipse.jdt.core Class Summary BufferChangedEvent A buffer changed event describes how a buffer has changed. ClasspathContainerInitializer Abstract base implementation of all classpath container initializer. ClasspathVariableInitializer Abstract base implementation of all classpath variable initializers. CompletionRequestorAdapter Adapter of the requestor interface ICompletionRequestor. CorrectionEngine This class is the entry point for source corrections. ElementChangedEvent An element changed event describes a change to the structure or contents of a tree of Java elements. Flags Utility class for decoding modifier flags in Java elements. JavaConventions Provides methods for checking Java−specific conventions such as name syntax. JavaCore The plug−in runtime class for the Java model plug−in containing the core (UI−free) support for Java projects. Signature Provides methods for encoding and decoding type and method signature strings. ToolFactory Factory for creating various compiler tools, such as scanners, parsers and compilers. Exception Summary JavaModelException A checked exception representing a failure in the Java model. 2.1.1.1 Package org.eclipse.jdt.core Description The Java model is the set of classes that model the objects associated with creating, editing, and building a Java program. 2.1.1.2 Package Specification This package contains the Java model classes, which implement Java specific behaviour for resources and further decompose java resources into model elements. 2.1.2 Package org.eclipse.jdt.core.compiler This package contains compiler associated infrastructure APIs. See: Description Interface Summary IProblem Description of a Java problem, as detected by the compiler or some of the underlying technology reusing the compiler. IScanner Definition of a Java scanner, as returned by the ToolFactory. ITerminalSymbols Maps each terminal symbol in the java−grammar into a unique integer. Exception Summary InvalidInputException Exception thrown by a scanner when encountering lexical errors. 2.1.2.1 Package org.eclipse.jdt.core.compiler Description This package contains compiler associated infrastructure APIs. 08/05/2002 25/48 2.1.2 Package org.eclipse.jdt.core.compiler JDT Plug−in Developer Guide 2.1.2.2 Package Specification This package contains some compiler tooling APIs, allowing to perform operations at a lower−level than using the JavaModel. 2.1.3 Package org.eclipse.jdt.core.dom The Java DOM is the set of classes that model Java program as a structured document. See: Description Interface Summary IBinding A binding represents a named entity in the Java language. IMethodBinding A method binding represents a method or constructor of a class or interface. IPackageBinding A package binding represents a named or unnamed package. ITypeBinding A type binding represents a class type, interface type, array type, a primitive type (including the special return type void), or the null type. IVariableBinding A variable binding represents either a field of a class or interface, or a local variable declaration (including formal parameters, local variables, and exception variables). Class Summary AnonymousClassDeclaration Anonymous class declaration AST node type. ArrayAccess Array access expression AST node type. ArrayCreation Array creation expression AST node type. ArrayInitializer Array initializer AST node type. ArrayType Type node for an array type. AssertStatement Assert statement AST node type. Assignment Assignment expression AST node type. Assignment.Operator Assignment operators (typesafe enumeration). AST Umbrella owner and abstract syntax tree node factory. ASTMatcher Concrete superclass and default implementation of an AST subtree matcher. ASTNode Abstract superclass of all Abstract Syntax Tree (AST) node types. ASTVisitor A visitor for abstract syntax trees. Block Block statement AST node type. BodyDeclaration Abstract base class of all AST nodes that represent body declarations that may appear in the body of a class or interface declaration. BooleanLiteral Boolean literal node. BreakStatement Break statement AST node type. CastExpression Cast expression AST node type. CatchClause Catch clause AST node type. CharacterLiteral Character literal nodes. ClassInstanceCreation Class instance creation expression AST node type. CompilationUnit Java compilation unit AST node type. ConditionalExpression Conditional expression AST node type. ConstructorInvocation Alternate constructor invocation expression AST node type. 26/48 08/05/2002 JDT Plug−in Developer Guide 2.1.2 Package org.eclipse.jdt.core.compiler ContinueStatement Continue statement AST node type. DoStatement Do statement AST node type. EmptyStatement Null statement AST node type. Expression Abstract base class of AST nodes that represent expressions. ExpressionStatement Expression statement AST node type. FieldAccess Field access expression AST node type. FieldDeclaration Field declaration node type. ForStatement For statement AST node type. IfStatement If statement AST node type. ImportDeclaration Import declaration AST node type. InfixExpression Infix expression AST node type. InfixExpression.Operator Infix operators (typesafe enumeration). Initializer Static or instance initializer AST node type. InstanceofExpression Instanceof expression AST node type. Javadoc AST node for a Javadoc comment. LabeledStatement Labeled statement AST node type. Message Error message used to report potential errors found during the AST parsing or name resolution. MethodDeclaration Method declaration AST node type. MethodInvocation Method invocation expression AST node type. Modifier Modifier flags. Name Abstract base class for all AST nodes that represent names. NullLiteral Null literal node. NumberLiteral Number literal nodes. PackageDeclaration Package declaration AST node type. ParenthesizedExpression Parenthesized expression AST node type. PostfixExpression Postfix expression AST node type. PostfixExpression.Operator Postfix operators (typesafe enumeration). PrefixExpression Prefix expression AST node type. PrefixExpression.Operator Prefix operators (typesafe enumeration). PrimitiveType Primitive type nodes. PrimitiveType.Code Primitive type codes (typesafe enumeration). QualifiedName AST node for a qualified name. ReturnStatement Return statement AST node type. SimpleName AST node for a simple name. SimpleType Type node for a named class or interface type. SingleVariableDeclaration VariableDeclaration declaration AST node type. Statement Abstract base class of AST nodes that represent statements. StringLiteral String literal nodes. SuperConstructorInvocation Super constructor invocation expression AST node type. SuperFieldAccess Simple or qualified "super" field access expression AST node type. SuperMethodInvocation Simple or qualified "super" method invocation expression AST node type. SwitchCase Switch case AST node type. 08/05/2002 27/48 2.1.3 Package org.eclipse.jdt.core.dom JDT Plug−in Developer Guide SwitchStatement Switch statement AST node type. SynchronizedStatement Synchronized statement AST node type. ThisExpression Simple or qualified "this" AST node type. ThrowStatement Throw statement AST node type. TryStatement Try statement AST node type. Type Abstract base class of all type AST node types. TypeDeclaration Type declaration AST node type. TypeDeclarationStatement Local type declaration statement AST node type. TypeLiteral Type literal AST node type. VariableDeclaration Abstract base class of all AST node types that declare a single local variable. VariableDeclarationExpression Local variable declaration expression AST node type. VariableDeclarationFragment Variable declaration fragment AST node type, used in field declarations, local variable declarations, and ForStatement initializers. VariableDeclarationStatement Local variable declaration statement AST node type. WhileStatement While statement AST node type. 2.1.3.1 Package org.eclipse.jdt.core.dom Description The Java DOM is the set of classes that model Java program as a structured document. 2.1.3.2 Package Specification This package contains the Java DOM classes. An API for manipulating a Java program as a structured document. In particular, it provides a full abstract syntax tree, which can be queried for resolved type information, and modified. 2.1.4 Package org.eclipse.jdt.core.eval Provides support for the evaluation of code snippets in a scrapbook or inside the debugger. See: Description Interface Summary ICodeSnippetRequestor A code snippet requestor implements a callback interface for installing the class files for a code snippet on the target and running it. IEvaluationContext An evaluation context supports evaluating code snippets. IGlobalVariable A global variable declared in an evaluation context. 2.1.4.1 Package org.eclipse.jdt.core.eval Description Provides support for the evaluation of code snippets in a scrapbook or inside the debugger. 2.1.4.2 Package Specification This packages provides support for the evaluation of code snippets in a scrapbook or inside the debugger. 28/48 08/05/2002 JDT Plug−in Developer Guide 2.1.5 Package org.eclipse.jdt.core.jdom 2.1.5 Package org.eclipse.jdt.core.jdom Provides a support for java document manipulation through the JDOM model. See: Description Interface Summary IDOMCompilationUnit Represents a Java compilation unit (.java source file). IDOMFactory A factory used to create document fragment (DF) nodes. IDOMField Represents a field declaration. IDOMImport Represents an import declaration. IDOMInitializer Represents an initializer. IDOMMember An IDOMMember defines functionality common to nodes, which can be members of types. IDOMMethod Represents a method declaration. IDOMNode Nodes represent structural fragments of a Java source file, also known as document fragments. IDOMPackage Represents a package declaration. IDOMType Represents a source type in a compilation unit, either as a top−level type or a member type. Class Summary DOMFactory Standard implementation of IDOMFactory, and the only means of creating JDOMs and document fragments. Exception Summary DOMException Unchecked exception thrown when an illegal manipulation of the JDOM is performed, or when an attempt is made to access/set an attribute of a JDOM node that source indexes cannot be determined for (in case the source was syntactically incorrect). 2.1.5.1 Package org.eclipse.jdt.core.jdom Description Provides a support for java document manipulation through the JDOM model. 2.1.5.2 Package Specification This package provides a support for java document manipulation throught the JDOM model. 2.1.6 Package org.eclipse.jdt.core.search Provides support for searching the workspace Java elements that match a particular description. See: Description Interface Summary IJavaSearchConstants This interface defines the constants used by the search engine. IJavaSearchResultCollector A IJavaSearchResultCollector collects search results from a search query to a SearchEngine. IJavaSearchScope An IJavaSearchScope defines where search result should be found by a SearchEngine. ISearchPattern A search pattern defines how search results are found. 08/05/2002 29/48 2.1.6 Package org.eclipse.jdt.core.search ITypeNameRequestor JDT Plug−in Developer Guide A ITypeNameRequestor collects search results from a searchAllTypeNames query to a SearchEngine. Class Summary SearchEngine A SearchEngine searches for java elements following a search pattern. 2.1.6.1 Package org.eclipse.jdt.core.search Description Provides support for searching the workspace Java elements that match a particular description. 2.1.6.2 Package Specification This package provides support for searching the workspace Java elements that match a particular description. In particular, it provides a search engine with a set of search patterns and search result requestors. 2.1.7 Package org.eclipse.jdt.core.util Provides a set of tools and utilities for manipulating .class files and Java model elements. See: Description Interface Summary IAttributeNamesConstants Description of attribute names as described in the JVM specifications. IBytecodeVisitor Description of a Java opcodes visitor. IClassFileAttribute This class represents a generic class file attribute. IClassFileDisassembler This interface is intended to be implemented to disassemble IClassFileReader onto a String using the proper line separator. IClassFileReader Description of a .class file. ICodeAttribute Description of a code attribute as described in the JVM specifications. IConstantPool Description of a constant pool as described in the JVM specifications. IConstantPoolConstant Description of constant pool constants as described in the JVM specifications. IConstantPoolEntry Description of a constant pool entry as described in the JVM specifications. IConstantValueAttribute Description of a constant value attribute as described in the JVM specifications. IExceptionAttribute Description of a constant value attribute as described in the JVM specifications. IExceptionTableEntry The class represents an entry in the exception table of a ICodeAttribute as specified in the JVM specifications. IFieldInfo Description of a field info as described in the JVM specifications. IInnerClassesAttribute Description of a inner class attribute as described in the JVM specifications. IInnerClassesAttributeEntry Description of a inner class info as described in the JVM specifications. ILineNumberAttribute Description of a line number attribute as described in the JVM specifications. ILocalVariableAttribute Description of a local variable attribute as described in the JVM specifications. ILocalVariableTableEntry Description of a local variable table entry as specified in the JVM specifications. IMethodInfo Description of a method info as described in the JVM specifications. IModifierConstants Definition of the modifier constants as specified in the JVM specifications. IOpcodeMnemonics Description of each opcode mnemonic according to the JVM specifications. ISourceAttribute Description of a source attribute as described in the JVM specifications. 30/48 08/05/2002 JDT Plug−in Developer Guide 2.1.7 Package org.eclipse.jdt.core.util Class Summary ByteCodeVisitorAdapter Adapter that implements the IBytecodeVisitor. OpcodeStringValues Description of each opcode mnemonic according to the JVM specifications. Exception Summary ClassFormatException Exception thrown by a class file reader when encountering a error in decoding information contained in a .class file. 2.1.7.1 Package org.eclipse.jdt.core.util Description Provides a set of tools and utilities for manipulating .class files and Java model elements. 2.1.7.2 Package Specification This package provides a set of tools and utilities for manipulating .class files and Java model elements. 2.1.8 Package org.eclipse.jdt.launching Application programming interfaces for interaction with the Eclipse Java launching support. See: Description Interface Summary IJavaLaunchConfigurationConstants Constant definitions for Java launch configurations. IRuntimeClasspathEntry Represents an entry on a runtime classpath. IRuntimeClasspathEntryResolver Resolves variable and/or container runtime classpath entries in the context of a launch configuration or Java project. IRuntimeClasspathProvider A classpath provider computes an unresolved classpath for a launch configuration, and resolves classpath entries for a launch configuration. IVMConnector A VM connector establishes a JDI connection with a debuggable virtual machine. IVMInstall Represents a particular installation of a VM. IVMInstallChangedListener A VM install changed listener is notified when the workspace default VM install changes, or when an attribute of a specific VM install changes. IVMInstallType Represents a particular type of VM for which there may be any number of VM installations. IVMRunner A VM runner starts a Java VM running a Java program. Class Summary AbstractJavaLaunchConfigurationDelegate Abstract implementation of a Java launch configuration delegate. AbstractVMInstall Abstract implementation of a VM install. AbstractVMInstallType Abstract implementation of a VM install type. AbstractVMRunner Abstract implementation of a VM runner. ExecutionArguments The execution arguments for running a Java VM. JavaRuntime The central access point for launching support. LibraryLocation The location of a library (for example rt.jar). 08/05/2002 31/48 2.1.8 Package org.eclipse.jdt.launching JDT Plug−in Developer Guide PropertyChangeEvent An event object describing a change to a named property. SocketUtil Utility class to find a port to debug on. StandardClasspathProvider Default implementation for classpath provider StandardSourcePathProvider Default implementation of source lookup path computation and resolution. VMRunnerConfiguration Holder for various arguments passed to a VM runner. 2.1.8.1 Package org.eclipse.jdt.launching Description Application programming interfaces for interaction with the Eclipse Java launching support. 2.1.8.2 Package Specification Provides support for describing installed Java runtime environments and launching Java virtual machines. 2.1.9 Package org.eclipse.jdt.launching.sourcelookup Application programming interfaces and classes for Eclipse Java source lookup. See: Description Interface Summary IJavaSourceLocation A source location defines the location of a repository of source code. Class Summary ArchiveSourceLocation Locates source elements in an acrhive (zip) in the local file system. DirectorySourceLocation Locates source elements in a directory in the local file system. JavaProjectSourceLocation Locates source elements in a Java project. JavaSourceLocator Locates source for a Java debug session by searching a configurable set of source locations. LocalFileStorage Implementation of storage for a local file (java.io.File). ZipEntryStorage Storage implementation for zip entries. 2.1.9.1 Package org.eclipse.jdt.launching.sourcelookup Description Application programming interfaces and classes for Eclipse Java source lookup. 2.1.9.2 Package Specification Provide support for Java debug source lookup. 2.1.10 Package org.eclipse.jdt.ui Application programming interfaces for interaction with the Eclipse Java User Interface. See: Description Interface Summary IContextMenuConstants 32/48 Constants for menu groups used in context menus for Java views and editors. 08/05/2002 JDT Plug−in Developer Guide 2.1.10 Package org.eclipse.jdt.ui IJavaElementSearchConstants Search scope constants for Java selection dialogs. IPackagesViewPart The standard Packages view presents a Java−centric view of the workspace. ISharedImages Standard images provided by the Java UI plug−in. ITypeHierarchyViewPart The standard type hierarchy view presents a type hierarchy for a given input class or interface. IWorkingCopyManager Interface for accessing working copies of ICompilationUnit objects. IWorkingCopyProvider Interface used for Java element content providers to indicate that the content provider can return working copy elements for members below compilation units. Class Summary JavaElementContentProvider Deprecated. use the StandardJavaElementContentProvider instead JavaElementImageDescriptor A JavaImageDescriptor consists of a base image and several adornments. JavaElementLabelProvider Standard label provider for Java elements. JavaElementSorter Sorter for Java elements. JavaUI Central access point for the Java UI plug−in (id "org.eclipse.jdt.ui"). OverrideIndicatorLabelDecorator LabelDecorator that decorates an method's image with override or implements overlays. PreferenceConstants Preference constants used in the JDT−UI preference store. ProblemsLabelDecorator LabelDecorator that decorates an element's image with error and warning overlays that represent the severity of markers attached to the element's underlying resource. ProblemsLabelDecorator.ProblemsLabelChangedEvent This is a special LabelProviderChangedEvent carring additional information whether the event orgins from a maker change. StandardJavaElementContentProvider A base content provider for Java elements. 2.1.10.1 Package org.eclipse.jdt.ui Description Application programming interfaces for interaction with the Eclipse Java User Interface. 2.1.10.2 Package Specification The package provides support classes for presenting Java elements in the user interface. The class JavaUI is the main access point to the Java user interface components. It allows to programmatically open editors on Java elements and open package and type prompter dialogs. The package exposes constants for retrieving Java user interface parts from the workbench registry. JavaUI gives access to the IWorkingCopyManager. It manages the working copies that are in use for Java compilation units. The interfaces ITypeHierarchyViewPart and IPackagesViewPart define the programming interface to interact with the type hierarchy and packages view parts. The classes JavaElementContentProvider and JavaElementLabelProvider support presenting Java elements in JFace viewers. 2.1.11 Package org.eclipse.jdt.ui.actions Application programming interfaces for Eclipse Java User Interface specific actions. See: Description Interface Summary 08/05/2002 33/48 2.1.10 Package org.eclipse.jdt.ui IJavaEditorActionDefinitionIds JDT Plug−in Developer Guide Defines the definition IDs for the Java editor actions. Class Summary AddGetterSetterAction Creates getter and setter methods for a type's fields. AddJavaDocStubAction Creates a Java Doc Stubs for the selected members. AddUnimplementedConstructorsAction Creates unimplemented constructors for a type. BuildActionGroup Contributes all build related actions to the context menu and installs handlers for the corresponding global menu actions. CCPActionGroup Action group that adds the copy, cut, paste actions to a view part's context menu and installs handlers for the corresponding global menu actions. CustomFiltersActionGroup Action group to add the filter action to a view part's toolbar menu. DeclarationsSearchGroup Action group that adds the search for declarations actions to a context menu and the global menu bar. ExternalizeStringsAction Externalizes the strings of a compilation unit. ExtractMethodAction Extracts the code selected inside a compilation unit editor into a new method. ExtractTempAction Extracts an expression into a new local variable and replaces all occurrences of the expression with the local variable. FindAction Abstract class for Java search actions. FindDeclarationsAction Finds declarations of the selected element in the workspace. FindDeclarationsInHierarchyAction Finds declarations of the selected element in its hierarchy. FindDeclarationsInWorkingSetAction Finds declarations of the selected element in working sets. FindImplementorsAction Finds implementors of the selected element in the workspace. FindImplementorsInWorkingSetAction Finds implementors of the selected element in working sets. FindReadReferencesAction Finds field read accesses of the selected element in the workspace. FindReadReferencesInHierarchyAction Finds field read accesses of the selected element in its hierarchy. FindReadReferencesInWorkingSetAction Finds field read accesses of the selected element in working sets. FindReferencesAction Finds references of the selected element in the workspace. FindReferencesInHierarchyAction Finds references of the selected element in its hierarchy. FindReferencesInWorkingSetAction Finds references of the selected element in working sets. FindStringsToExternalizeAction Find all Strings in a package or project that are not externalized yet. FindWriteReferencesAction Finds field write accesses of the selected element in the workspace. FindWriteReferencesInHierarchyAction Finds field write accesses of the selected element in its hierarchy. FindWriteReferencesInWorkingSetAction Finds field write accesses of the selected element in working sets. GenerateActionGroup Action group that adds the source and generate actions to a part's context menu and installs handlers for the corresponding global menu actions. ImplementorsSearchGroup Action group that adds the search for implementors actions to a context menu and the global menu bar. ImportActionGroup Action group to add the Import and Export action to a view part's context menu. InlineTempAction Inlines the value of a local variable at all places where a read reference is used. JavaSearchActionGroup Action group that adds the Java search actions to a context menu and the global menu bar. JdtActionConstants Action ids for standard actions, for groups in the menu bar, and for actions in context menus of JDT views. MemberFilterActionGroup Action Group that contributes filter buttons for a view parts showing methods and fields. ModifyParametersAction Action to start the modify parameters refactoring. 34/48 08/05/2002 JDT Plug−in Developer Guide 2.1.11 Package org.eclipse.jdt.ui.actions MoveAction This action moves Java elements to a new location. NavigateActionGroup Action group that adds the open and show actions to a context menu and the action bar's navigate menu. OpenAction This action opens a Java editor on a Java element or file. OpenEditorActionGroup Action group that adds the actions opening a new editor to the context menu and the action bar's navigate menu. OpenExternalJavadocAction This action opens the selected element's Javadoc in an external browser. OpenJavaBrowsingPerspectiveAction Action to programmatically open a Java perspective. OpenJavaPerspectiveAction Action to programmatically open a Java perspective. OpenProjectAction Action to open a closed project. OpenSuperImplementationAction The action opens a Java editor on the selected method's super implementation. OpenTypeHierarchyAction This action opens a type hierarchy on the selected type. OpenViewActionGroup Action group that adds actions to open a new JDT view part or an external viewer to a context menu and the global menu bar. OrganizeImportsAction Organizes the imports of a compilation unit. OrganizeImportsAction.ObjectDelegate OverrideMethodsAction Adds unimplemented methods of a type. ProjectActionGroup Adds actions to open and close a project to the global menu bar. PullUpAction Action to pull up method and fields into a superclass. ReadReferencesSearchGroup Action group that adds the search for read references actions to a context menu and the global menu bar. RefactorActionGroup Action group that adds refactor actions (e.g. ReferencesSearchGroup Action group that adds the search for references actions to a context menu and the global menu bar. RefreshAction Action for refreshing the workspace from the local file system for the selected resources and all of their descendents. RenameAction Renames a Java element or workbench resource. SelectionDispatchAction Action that dispatches the IAction#run() and the ISelectionChangedListener#selectionChanged according to the type of the selection. SelfEncapsulateFieldAction Action to run the self encapsulate field refactoring. ShowActionGroup Action group that adds the show actions to a context menu and the action bar's navigate menu. ShowInNavigatorViewAction Reveals the selected element in the resource navigator view. ShowInPackageViewAction This action reveals the currently selected Java element in the package explorer. SurroundWithTryCatchAction Action to surround a set of statements with a try/catch block. WorkingSetFindAction Wraps a JavaElementSearchActions to find its results in the specified working set. WriteReferencesSearchGroup Action group that adds the search for write references actions to a context menu and the global menu bar. 2.1.11.1 Package org.eclipse.jdt.ui.actions Description Application programming interfaces for Eclipse Java User Interface specific actions. 2.1.11.2 Package Specification The package provides actions and action groups to populate tool bars, global menu bars and context menus with JDT specific functionality. It is recommended that clients use action groups to populate menus and tool bars instead of adding actions directly. 08/05/2002 35/48 2.1.12 Package org.eclipse.jdt.ui.jarpackager JDT Plug−in Developer Guide Clients are allowed to instantiate classes from this package. The classes are not intended to be subclassed. All actions and groups require that the selection provided by the site, view part or page passed to the action's or group's constructor is of type org.eclipse.jface.viewers.IStructuredSelection . 2.1.12 Package org.eclipse.jdt.ui.jarpackager Provides classes and interfaces to generate a JAR file. See: Description Interface Summary IJarDescriptionReader Reads the description file of a JAR package data object into such an object. IJarDescriptionWriter Writes the description file of a JAR package data object. IJarExportRunnable A runnable which executes a JAR export operation within the workspace. IManifestProvider A manifest provider creates manifest files. Class Summary JarPackageData Model for a JAR package. JarWriter Creates a JAR file for the given JAR package data. 2.1.12.1 Package org.eclipse.jdt.ui.jarpackager Description Provides classes and interfaces to generate a JAR file. This package provides the interfaces and classes for exporting a set of resources to a JAR file via runnable. It offers hooks to extend the JarPackageData to load and store the JarPackageData and to write the JAR itself. 2.1.12.2 Package Specification The JarPackageData contains all necessary information to generate a JAR file. This class can be extended to provide additional data or to plug−in a custom JarWriter. The default runnable which creates the JAR can be replaced by implementing IJarExportRunnable. The same applies for the manifest provider (IManifestProvider) and the classes which save (IJarDescriptionWriter) and read (IJarDescriptionReader) the JarPackageData. 2.1.13 Package org.eclipse.jdt.ui.text Application programming interfaces for interaction with the Eclipse Java User Interface text support. See: Description Interface Summary IColorManager Manages SWT color objects for given color keys and given RGB objects. IColorManagerExtension A color manager extension for extending IColorManager instances with new functionality. IJavaColorConstants Color keys used for syntax highlighting Java code and JavaDoc compliant comments. Class Summary JavaSourceViewerConfiguration Configuration for a source viewer which shows Java code. JavaTextTools Tools required to configure a Java text viewer. 36/48 08/05/2002 JDT Plug−in Developer Guide 2.1.13 Package org.eclipse.jdt.ui.text 2.1.13.1 Package org.eclipse.jdt.ui.text Description Application programming interfaces for interaction with the Eclipse Java User Interface text support. 2.1.13.2 Package Specification Support for presenting Java text. The class JavaTextTools provides access to the different scanners to partition and color Java source code. The class JavaSourceViewerConfiguration defines a standard configuration for a Java source viewer. 2.1.14 Package org.eclipse.jdt.ui.text.java.hover Application programming interfaces for interaction with the Eclipse Java Editor. See: Description Interface Summary IJavaEditorTextHover Provides a hover popup which appears on top of an editor with relevant display information. 2.1.14.1 Package org.eclipse.jdt.ui.text.java.hover Description Application programming interfaces for interaction with the Eclipse Java Editor. 2.1.14.2 Package Specification Support for presenting text hovers in Java editors. The interface IJavaEditorTextHover defines the programming interface for a text hover. 2.1.15 Package org.eclipse.jdt.ui.wizards Application programming interfaces for interaction with the Eclipse Java User Interface wizards. See: Description Interface Summary IClasspathContainerPage A classpath container page allows the user to create a new or edit an existing classpatch container entry. Class Summary JavaCapabilityConfigurationPage Standard wizard page for creating new Java projects. NewClassWizardPage Wizard page to create a new class. NewContainerWizardPage Wizard page that acts as a base class for wizard pages that create new Java elements. NewElementWizardPage Base class for wizard page responsible to create Java elements. NewInterfaceWizardPage Wizard page to create a new interface. NewJavaProjectWizardPage Standard wizard page for creating new Java projects. NewPackageWizardPage Wizard page to create a new package. NewTypeWizardPage The class NewTypeWizardPage contains controls and validation routines for a 'New Type WizardPage'. NewTypeWizardPage.ImportsManager Class used in stub creation routines to add needed imports to a compilation unit. 08/05/2002 37/48 2.1.15 Package org.eclipse.jdt.ui.wizards JDT Plug−in Developer Guide 2.1.15.1 Package org.eclipse.jdt.ui.wizards Description Application programming interfaces for interaction with the Eclipse Java User Interface wizards. 2.1.15.2 Package Specification Provide access to the wizard pages for creating Java elements. Currently only the standard wizard page for creating Java projects is available. 2.1.16 Package org.eclipse.jdt.debug.core Interface Summary IEvaluationRunnable A runnable that represents one logical evaluation to be run in a target thread. IJavaArray A value referencing an array on a target VM. IJavaArrayType The type of an array on a Java debug target. IJavaBreakpoint A breakpoint specific to the Java debug model. IJavaBreakpointListener Provides event and error notification for Java breakpoints. IJavaClassObject An object referencing an instance of java.lang.Class on a target VM. IJavaClassType The class of an object on a Java debug target. IJavaDebugTarget A Java virtual machine. IJavaExceptionBreakpoint A breakpoint that suspends execution when a corresponding exception is thrown in a target VM. IJavaFieldVariable A variable that contains the value of an instance or class variable. IJavaHotCodeReplaceListener Notification of hot code replace failure and success. IJavaInterfaceType An interface an object implements on a Java debug target. IJavaLineBreakpoint A breakpoint that suspend execution when a particular line of code is reached. IJavaMethodBreakpoint A method breakpoint suspends execution when a method is entered or exited. IJavaMethodEntryBreakpoint A method entry breakpoint suspends execution on the first executable line of a method when entered. IJavaModifiers Modifiers common to Java debug elements that have associated Java member declarations. IJavaObject A value referencing an object on a target VM. IJavaPatternBreakpoint A line breakpoint installed in types associated with a specific source file (based on source file name debug attribute) and whose fully qualified name matches a specified pattern. IJavaPrimitiveValue A primitive value on a Java debug target. IJavaStackFrame A stack frame in a thread on a Java virtual machine. IJavaTargetPatternBreakpoint A line breakpoint installed in types associated with a specific source file (based on source file name debug attribute) and whose fully qualified name matches a specified pattern per target. IJavaThread A thread in a Java virtual machine. IJavaType The type of a value on a Java debug target − a primitive data type, class, interface, or array. IJavaValue An object, primitive data type, or array, on a Java virtual machine. IJavaVariable A local variable, field slot, or receiver (this) in a Java virtual machine. IJavaWatchpoint A breakpoint on a field. Class Summary JDIDebugModel 38/48 Provides utility methods for creating debug targets and breakpoints specific to the JDI debug model. 08/05/2002 JDT Plug−in Developer Guide 2.1.17 Package org.eclipse.jdt.debug.eval 2.1.17 Package org.eclipse.jdt.debug.eval Interface Summary IAstEvaluationEngine An evaluation engine that performs evaluations by interpretting abstract syntax trees. IClassFileEvaluationEngine An evaluation engine that performs evaluations by deploying and executing class files locally. ICompiledExpression A compiled expression can be compiled once and evaluated multiple times in a runtime context. IEvaluationEngine An evaluation engine performs an evalutaion of a code snippet or expression in a specified thread of a debug target. IEvaluationListener Evaluation results are reported to evaluation listeners on the completion of an evaluation. IEvaluationResult The result of an evaluation. Class Summary EvaluationManager The evaluation manager provides factory methods for creating evaluation engines. 2.1.18 Package org.eclipse.jdt.debug.ui Provides an implementation of a source locator for the Java debug model. See: Description Interface Summary IJavaDebugUIConstants Constant definitions for Java debug UI plug−in. Class Summary JavaUISourceLocator A source locator that prompts the user to find source when source cannot be found on the current source lookup path. 2.1.18.1 Package org.eclipse.jdt.debug.ui Description Provides an implementation of a source locator for the Java debug model. 2.1.18.2 Package Specification This package provides a source locator for the Java debug model. The source locator prompts the user for source, when source cannot be found on the source lookup path. 2.1.19 Package org.eclipse.jdt.debug.ui.launchConfigurations Provides an implementation launch configuration tabs for local and remote Java applications. See: Description Class Summary JavaArgumentsTab A launch configuration tab that displays and edits program arguments, VM arguments, and working directory launch configuration attributes. JavaClasspathTab 08/05/2002 39/48 2.1.19 Package org.eclipse.jdt.debug.ui.launchConfigurations JDT Plug−in Developer Guide A launch configuration tab that displays and edits the user and bootstrap classes comprising the classpath launch configuration attribute. JavaConnectTab A launch configuration tab that displays and edits the project associated with a remote connection and the connector used to connect to a remote VM. JavaJRETab A launch configuration tab that displays and edits the VM install launch configuration attributes. JavaMainTab A launch configuration tab that displays and edits project and main type name launch configuration attributes. JavaSourceLookupTab A launch configuration tab that displays and edits source lookup path launch configuration attributes. 2.1.19.1 Package org.eclipse.jdt.debug.ui.launchConfigurations Description Provides an implementation launch configuration tabs for local and remote Java applications. 2.1.19.2 Package Specification This package provides launch configuration tabs for local and remote Java applications. 2.2 JDT Extension Points The following extension points can be used to extend the capabilities of the JDT infrastructure: • org.eclipse.jdt.core.classpathVariableInitializer • org.eclipse.jdt.core.classpathContainerInitializer • org.eclipse.jdt.core.codeFormatter • org.eclipse.jdt.launching.vmInstallTypes • org.eclipse.jdt.launching.vmConnectors • org.eclipse.jdt.launching.runtimeClasspathProviders • org.eclipse.jdt.launching.runtimeClasspathEntryResolvers • org.eclipse.jdt.debug.ui.vmInstallTypePage • org.eclipse.jdt.ui.javaElementFilters • org.eclipse.jdt.ui.javaEditorTextHover • org.eclipse.jdt.ui.classpathContainerPage 2.2.1 Classpath Variable Initializer Identifier: org.eclipse.jdt.core.classpathVariableInitializer Description: This extension point provides a mechanism for contributing an classpath variable initializer that will be used when the corresponding classpath variable is initialized. Configuration Markup: <!ELEMENT classpathVariableInitializer> <!ATTLIST classpathVariableInitializer variable CDATA #REQUIRED class CDATA #REQUIRED > • variable the name of the classpath variable • class the class that implements this classpath variable initializer. The class must implement a public subclass of org.eclipse.jdt.core.ClasspathVariableInitializer with a public 0−argument constructor Example: Example of an ClasspathVariableInitializer for a classpath variable named "FOO": <extension point="org.eclipse.jdt.core.classpathVariableInitializer"> <classpathVariableInitializer variable="FOO" class="com.example.CPVInitializer"/> </extension> 40/48 08/05/2002 JDT Plug−in Developer Guide 2.2.2 Classpath Container Initializer 2.2.2 Classpath Container Initializer Identifier: org.eclipse.jdt.core.classpathContainerInitializer Description: This extension point provides a mechanism for contributing an classpath container initializer that will be used when the corresponding classpath container is initialized. Configuration Markup: <!ELEMENT classpathContainerInitializer> <!ATTLIST classpathContainerInitializer id CDATA #REQUIRED class CDATA #REQUIRED > • id an unique name identifying all containers for which this resolver will be activated. • class the class that implements this container resolver. The class must implement a public subclass of org.eclipse.jdt.core.ClasspathContainerInitializer with a public 0−argument constructor. Example: The following is an example of an ClasspathContainerInitializer for a classpath container named "JDK/1.2": <extension point="org.eclipse.jdt.core.classpathContainerInitializer"> <classpathContainerInitializer id="JDK/1.2" class="com.example.MyInitializer"/> </extension> 2.2.3 Code Formatter Identifier: org.eclipse.jdt.core.codeFormatter Description: This extension point provides a mechanism for contributing a code formatter that can be used using the format command in the Java editor. Configuration Markup: <!ELEMENT codeFormatter> <!ATTLIST codeFormatter class CDATA #REQUIRED > • class the class that defines the code formatter implementation. The class must be a public implementatiom of org.eclipse.jdt.core.ICodeFormatter with a public 0−argument constructor. Example: The following is an example of a code formatter extension point: <extension point="org.eclipse.jdt.core.codeFormatter"> <codeFormatter class="com.example.MyCodeFormatter"/> </extension> In the above example, the format command will call the format method defined in com.example.MyCodeFormatter. 2.2.4 Java Runtime Classpath Entry Resolvers Identifier: org.eclipse.jdt.launching.runtimeClasspathEntryResolvers Description: This extension point allows clients to dynamically resolve entries used on the runtime classpath and source lookup path, for corresponding classpath variables and classpath containers. 08/05/2002 41/48 2.2.5 Java Runtime Classpath Providers JDT Plug−in Developer Guide Configuration Markup: <!ELEMENT runtimeClasspathEntryResolver EMPTY> <!ATTLIST runtimeClasspathEntryResolver id CDATA #REQUIRED class CDATA #REQUIRED variable CDATA #OPTIONAL container CDATA #OPTIONAL > • id − a unique identifier that can be used to reference this resolver • class − the class that implements this resolver. The class must implement IRuntimeClasspathEntryResolver. • variable − the name of the classpath variable this resolver is registered for. • container − the identifier of the classpath container this resolver is registered for. At least one of variable or container must be specified, and at most one resolver can be registered for a variable or container. Examples: The following is an example of a resolver: <extension point="org.eclipse.jdt.launching.runtimeClasspathEntryResolvers"> <runtimeClasspathEntryResolver class="com.example.ResolverImplementation" id="com.example.ResolverId"> variable="CLASSPATH_VARIABLE"> </runtimeClasspathEntryResolver> </extension> 2.2.5 Java Runtime Classpath Providers Identifier: org.eclipse.jdt.launching.classpathProviders Description: This extension point allows clients to dynamically compute and resolve classpaths and source lookup paths for Java launch configurations. Configuration Markup: <!ELEMENT classpathProviders EMPTY> <!ATTLIST classpathProvider id CDATA #REQUIRED class CDATA #REQUIRED > • id − a unique identifier that can be used to reference this classpath provider • class − the class that implements this classpath provider. The class must implement IRuntimeClasspathProvider. Examples: The following is an example of a classpath provider: <extension point="org.eclipse.jdt.launching.classpathProvider"> <classpathProvider class="com.example.ProviderImplementation" id="com.example.ProviderId"> </classpathProvider> </extension> 2.2.6 Java VM Connectors Identifier: org.eclipse.jdt.launching.vmConnectors Description: This extension point represents different kinds of connections to remote VMs. Each extension must implement org.eclipse.jdt.launching.IVMConnector. An IVMConnector is responsible for establishing a connection with a remote 42/48 08/05/2002 JDT Plug−in Developer Guide 2.2.7 Java VM Install Types VM. Configuration Markup: <!ELEMENT vmConnector EMPTY> <!ATTLIST vmConnector id CDATA #REQUIRED class CDATA #REQUIRED > • id − a unique identifier that can be used to reference this IVMConnector • class − the class that implements this connector. The class must implement IVMConnector. Examples: The following is an example of an IVMConnector: <extension point="org.eclipse.jdt.launching.vmConnectors"> <vmConnector class="com.example.ConnectorImplementation" id="com.example.ConnectorId"> </vmConnector> </extension> Supplied Implementation: An implementation of a standard socket attach connector is provided. 2.2.7 Java VM Install Types Identifier: org.eclipse.jdt.launching.vmInstallTypes Description: This extension point represents different kinds of Java runtime environments and development kits. Each extension must implement org.eclipse.jdt.launching.IVMInstallType. An IVMInstallType is responsible for creating and managing a set of instances of its corresponding IVMInstall class. Through creating different IVMInstall objects, an IVMInstallType allows for specific behaviour for various Java VMs. A UI for managing IVMInstalls is provided by the Java UI plugin. Configuration Markup: <!ELEMENT vmInstallType EMPTY> <!ATTLIST vmInstallType id CDATA #REQUIRED class CDATA #REQUIRED > • id − a unique identifier that can be used to reference this IVMInstallType • class − the class that implements this VM install type. The class must implement IVMInstallType. Examples: The following is an example of an IVMInstallType for the J9 VM: <extension point="org.eclipse.jdt.launching.vmInstallTypes"> <vmInstallType class="org.eclipse.jdt.internal.launching.j9.J9VMInstallType" id="org.eclipse.jdt.internal.launching.j9.J9Type"> </vmInstallType> </extension> Supplied Implementation: Abstract implementations of IVMInstall and IVMInstallType are provided. The Java UI plugin defines a VM install type for the standard 1.2/1.3 level JRE. 08/05/2002 43/48 2.2.8 VM Install Type UI Page JDT Plug−in Developer Guide 2.2.8 VM Install Type UI Page Identifier: org.eclipse.jdt.debug.ui.vmInstallTypePage Description: This extension point provides a mechanism for contributing UI that will appear in the JRE tab of the launch configuration dialog. The UI is shown only when a VM of the specified install type is selected in the JRE tab. Configuration Markup: <!ELEMENT vmInstallTypePage> <!ATTLIST vmInstallTypePage id CDATA #REQUIRED vmInstallTypeID class CDATA #REQUIRED CDATA #REQUIRED • id specifies a unique identifier for this vm install type UI page. • vmInstallTypeID specifies VM install type that this UI page is applicable to (corresponds to the id of a VM install type). • class specifies a fully qualified name of a Java class that implements ILaunchConfigurationTab. Examples: The following is an example of a VM install type page extension point: <extension point="org.eclipse.jdt.debug.ui.vmInstallTypePage"> <vmInstallTypePage id="com.example.ExampleVMInstallTypePage" vmInstallTypeID="com.example.ExampleVMInstallTypeIdentifier" class="com.example.ExampleVMInstallTypePage" </vmInstallTypePage> </extension> In the above example, the contributed page will be shown in the JRE tab of the launch configuration dialog whenever the currently selected JRE has a VM Install type identifier of com.example.ExampleVMInstallTypeIdentifier. API Information: Value of the attribute class must be a fully qualified name of a Java class that implements the interface org.eclipse.debug.ui.ILaunchConfigurationTab. 2.2.9 Java Element Filters Identifier: org.eclipse.jdt.ui.javaElementFilters Description: This extension point is used to extend Java UI views with filters. Configuration Markup: <!ELEMENT filter EMPTY> <!ATTLIST filter id CDATA #IMPLIED name CDATA #IMPLIED description CDATA #IMPLIED viewId CDATA #IMPLIED class* CDATA #IMPLIED enabled (true | false) #IMPLIED pattern* CDATA #IMPLIED > *) exactly one of them must be present • id − a unique id that will be used to identify this filter. • name − a unique name that allows to identify this filter in the UI. This attribute should be a translated string. Though this attribute is not required for pattern filters (i.e. those using the pattern attribute) we suggest to provide a name anyway, otherwise the pattern string itself would be used to represent the filter in the UI. • description − a short description for this filter. This attribute should be a translated string. • viewId − the id of the view where this filter is contributed. If this attribute is missing then the filter will be contributed to all views which use the org.eclipse.jdt.ui.actions.CustomFiltersActionGroup . 44/48 08/05/2002 JDT Plug−in Developer Guide 2.2.10 Java Editor Text Hovers • class − the name of the class used to filter the view. The class must extend org.eclipse.jface.viewers.ViewerFilter • enabled − the filter will be enabled if this attribute is present and its value is true. Most likely the user will be able to override this setting in the UI. • pattern − elements whose name matches this pattern will be hidden. This attribute is here for backward compatibility and should no longer be used. All views that allow to plug−in a filter also allow to add pattern filters directly via UI. Examples: The following is an example of a Java element filter definition. It filters out libraries and is initially disabled: <extension point="org.eclipse.jdt.ui.javaElementFilters"> <filter id="org.eclipse.jdt.ui.PackageExplorer.LibraryFilter" name="%HideReferencedLibraries.label" description="%HideReferencedLibraries.description" viewId="org.eclipse.jdt.ui.PackageExplorer" class="org.eclipse.jdt.internal.ui.filters.LibraryFilter" enabled="false"> </filter> </extension> 2.2.10 Java Editor Text Hovers Identifier: org.eclipse.jdt.ui.javaEditorTextHovers Description: This extension point is used to plug−in text hovers in a Java editor. Configuration Markup: <!ELEMENT hover EMPTY> <!ATTLIST hover id CDATA #REQUIRED class CDATA #REQUIRED > • id − a unique id that will be used to identify this filter, typically the same as the fully qualified class name. • class − the fully qualified class name implementing the interface org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover. Examples: The following is an example of a hover defintion: <extension point="org.eclipse.jdt.ui.javaEditorTextHover"> <hover id="org.eclipse.example.jdt.internal.debug.ui.JavaDebugHover" class="org.eclipse.example.jdt.internal.debug.ui.JavaDebugHover"> </hover> </extension> 2.2.11 Classpath Container Page Identifier: org.eclipse.jdt.ui.classpathContainerPage Description: This extension point allows to add UI to the libraries tab of Java build path setting page to create or edit a classpath container. The extension point defines UI for an already in JDT core defined classpath container. Configuration Markup: 08/05/2002 45/48 2.3 Other Reference Information <!ELEMENT <!ATTLIST id name class > JDT Plug−in Developer Guide classpathContainerPage EMPTY> classpathContainerPage CDATA #IMPLIED CDATA #IMPLIED CDATA #IMPLIED • id − this id must correspond to classpath container defined via the extension point org.eclipse.jdt.core.classpathVariableInitializer in JDT core. • name − a unique name that allows to identify this classpath container in the UI. This attribute should be a translated string. • class − the name of the class that implements this classpath container page. The class must be public and must implement org.eclipse.jdt.ui.wizards.IClasspathContainerPage with a public 0−argument constructor. Examples: The following is an example of a classpath container page: <extension point="org.eclipse.jdt.ui.classpathContainerPage"> <classpathContainerPage id="com.example.jre.classpathContainer" name="JRE System Libraries" class="com.example.NewJDKEntryPage" </classpathContainerPage> </extension> 2.3 Other Reference Information The following specifications, white papers, and design notes describe various aspects of the Java development tooling. • Map of Eclipse Java Development Tooling Plug−ins 2.3.1 Eclipse Platform Map of Java Development Tooling Plug−ins The Eclipse Java development tooling provides a comprehensive Java development environment. The Java development tooling itself is divided up into a number of separate plug−ins. The following table shows which API packages are found in which plug−ins (the most commonly referenced API packages are highlighted). This table is useful for determing which plug−ins a given plug−in should include as prerequisites. API Package com.sun.jdi[.*] org.eclipse.jdi[.*] org.eclipse.jdt.debug[.*] org.eclipse.jdt.debug.ui[.*] org.eclipse.jdt.core[.*] org.eclipse.jdt.launching[.*] org.eclipse.jdt.ui[.*] 46/48 Plug−in id org.eclipse.jdt.debug org.eclipse.jdt.debug.ui org.eclipse.jdt.core org.eclipse.jdt.launching org.eclipse.jdt.ui 08/05/2002 3 JDT Questions Index 3.1 JDT Core • What is available in the JDT Core API Packages? • How do I launch a Java program from the platform? • How do I programmatically compile a Java program? • How do I setup a project's classpath? • How do I manipulate Java code? • How do I use the Java search engine? • What are the JDT Core options? • How do I programmatically use CodeAssist and CodeSelect? • How are Java projects, folders, and files different from regular resources? 3.2 JDT UI • What is available in the JDT UI packages? • How do I programmatically launch a Java editor on a file? • How do I create a Java specific prompter dialog? • How do I present Java elements in a standard JFace viewer? • How do I write a Jar file? • How do I create a customized new Java element wizard page? • How do I manipulate Java code with a preview in a Java editor? 08/05/2002 47/48 3 JDT Questions Index 48/48 JDT Plug−in Developer Guide 08/05/2002