Create a JDT Project in Eclipse

        JDT stands for Java development tools, the sub-project of the Eclipse project that develops tools for programming in Java. This includes a Java compiler, incremental builder, editors, wizards, content assist, and all the other features of a first class Java IDE.
        The JDT Core component is the plug-in that defines the core Java elements and API. This Core component can be included inside our own plugin and can be used to search, compile and manipulate Java code outside an IDE. This is because the JDT/Core infrastructure has no built-in JDK version dependencies, and it also does not depend on any particular Java UI.

Below are some of the activities that can be performed by using the JDT Core plug-in :
  1. Programmatically manipulate Java resources, such as creating projects, generating Java source code, performing builds, or detecting problems in code.
  2. Searching the workspace's Java model for Java elements that match a particular description.
  3. Generating Abstract Syntax Trees (AST) that can be used for examining the structure of a compilation unit down to the statement level.
  4. Formatting of compilation units, types, statements, expressions, etc.

        JDT is supported by 3 pillars: Java Model, Search Engine, and AST. More info about JDT can be found from here. Here is couple of nice presentations which briefly describes all JDT fundamentals and features - JDT Fundamentals 2010 and JDT Fundamentals. JDT allows you to access Java Code using  AST (Abstract Syntax Tree). AST is a Document Object Model for Java, where each code element is represented as AST Nodes. It gives you a detailed tree structureof the Java source code. Some of the ASTNodes are MethodDeclaration, FieldDeclaration, MethodInvocation, VariableDeclarationStatement, ExpressionStatement etc. In this post we will be using this AST functionality to retrieve information from a Java Source File.

        At first we need to create a plug-in project which uses JDT Core plugin. Instructions on creating a plug-in project in eclipse can be found from here. Name the new project JDT_Basic. Now to use the JDT core functionality we need to add it as a plug-in to our project. We can do this from the 'Dependencies' tab (view this tab by opening the plugin.xml file). Click on the 'Add' button and add the 'org.eclipse.jdt.core' plug-in. This way we have included the JDT Core plug-in our project and thus will be able to use the AST functionalities.

 

        For running this plugin project we will be using the 'applications' extension. For this, double click on the plugin.xml file and open the 'Extensions' tab. Remove the 'actionSets' extension and add the 'applications' extension (org.eclipse.core.runtime.applications). Expand the extension in the window and create a new run by right clicking and choosing New > run. Specify the class as 'jdt_basic.JDTClass' and click on the 'class' label to create the Class.


        This class will be used to invoke our JDT application. The 'start' method of the application class denotes the starting point of the plug-in application, whereas the 'stop' method is invoked at the end of the application. Using this application class we will try to implement a simple activity, to list all the methods in a Java file.

        Here is how we are going to accomplish this. At first we will read the content of the Java file using a String Buffer. Using this content(source) we will create a CompilationUnit for the Java file. This CompilationUnit gives you an AST representation of the Java File. To traverse the various AST nodes of this CompilationUnit you can use the ASTVisitor pattern. In this example we will list out the Class methods by traversing the MethodDeclaration node.

        Here is the code for the JDTClass. Each step in the code has documented with comments for clear understanding. If you have any questions or queries, please comment. I will be more than happy to help you out.

package jdt_basic;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;

/** 
 * This class provides basic JDT functionality.
*/
public class JDTClass implements IApplication {
    
    /** 
     * The starting point of the plug-in application.
     * Visit the Code specified as path and list the methods inside the class.
     */
    @Override
    public Object start(IApplicationContext context) throws Exception {

        // Get the source code of the java class file - change path to your file's path.
        final StringBuffer sourceCode = getSource("d:\\HelloWorld.java");
        // Define a new ASTParser.
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        // Parse the class as a compilation unit.
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        // Supply the class code as character array.
        parser.setSource(sourceCode.toString().toCharArray());
        parser.setResolveBindings(true);
        // Get the compiled class as a compilation unit  
        final CompilationUnit compiledClassUnit = (CompilationUnit) parser.createAST(null);
        // Instantiate a new ASTVisitor class that will determine which nodes are visited during an AST traversal
        compiledClassUnit.accept(new ASTVisitor() {
            @Override
            // Visit the MethodDeclaration node - denotes the declaration of methods in a class
            public boolean visit(MethodDeclaration node) {
                // Show the visited method in console.
                System.out.println("Method " + node.getName().getFullyQualifiedName() + " is visited");
                return true;
            }
        });
        return IApplication.EXIT_OK;
    }
    
    /**
     * Returns the source code of the java class file as string buffer.
     * @param path the path of the Java class file
     * @return StringBuffer string buffer containing the source code
     */
    private static StringBuffer getSource(String path) {

        // Define string buffer for holding the source
        final StringBuffer buffer = new StringBuffer();
        try {
            // Read the file line by line and append to string buffer.
            File javaFile = new File(path);
            BufferedReader in = new BufferedReader(new FileReader(javaFile)); 
            String line = null;
            while (null != (line = in.readLine())) {
                buffer.append(line).append("\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /** 
     * The end point of the plug-in application.
     */
    public void stop() {
        // TODO Auto-generated method stub
    }
}

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
 

Copyright © 2012 | ScriptSplash | Powered by Blogger Templates