Search code examples
eclipsecommand-lineeclipse-pdt

Is it possible to create a command line JDT application?


I want to create a command line application which does analysis of Java code. The Eclipse JDT seems like the right tool for the job, however every tutorial I can find on the JDT starts up the JDT as an Eclipse plugin.

I would expect something like this:

public static void main(String[] args) throws Exception {
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    ...
}

to get started. However getWorkspace() throws an exception that the service is not started.


Solution

  • If you want to leverage JDT you have to start eclipse. You can use the extension point "org.eclipse.core.runtime.applications" to create a minimal application that starts from the command line.

    1. Create a new Plugin-Project.
    2. Add "org.eclipse.core.runtime" and "org.eclipse.core.resources" to the dependencies.
    3. Create an extension for "org.eclipse.core.runtime.applications".
    4. Create a class that implements "org.eclipse.equinox.app.IApplication" and reference it in your extension.

    My plugin.xml looks like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <?eclipse version="3.4"?>
    <plugin>
       <extension
             id="id2"
             point="org.eclipse.core.runtime.applications">
          <application
                cardinality="singleton-global"
                thread="main"
                visible="true">
             <run class="testapplication.Application1">
             </run>
          </application>
       </extension>
    </plugin>
    

    MANIFEST.MF:

    Manifest-Version: 1.0
    Bundle-ManifestVersion: 2
    Bundle-Name: TestApplication
    Bundle-SymbolicName: TestApplication;singleton:=true
    Bundle-Version: 1.0.0.qualifier
    Bundle-Activator: testapplication.Activator
    Require-Bundle: org.eclipse.core.runtime,
     org.eclipse.core.resources
    Bundle-ActivationPolicy: lazy
    Bundle-RequiredExecutionEnvironment: JavaSE-1.6
    

    Application1.java:

    package testapplication;
    
    import org.eclipse.core.resources.ResourcesPlugin;
    import org.eclipse.equinox.app.IApplication;
    import org.eclipse.equinox.app.IApplicationContext;
    
    public class Application1 implements IApplication {
    
        @Override
        public Object start(IApplicationContext context) throws Exception {
            System.out.println("Hello eclipse at "
                    + ResourcesPlugin.getWorkspace().getRoot().getRawLocation());
            return IApplication.EXIT_OK;
        }
    
        @Override
        public void stop() {
            // nothing to do at the moment
        }
    
    }
    

    Output is:

    Hello eclipse at D:/Arne/workspaces/runtime-TestApplication.id2