Wednesday, July 25, 2007

Creating a new project in Eclipse Programatically

If you have done Eclipse plugin development you would know that any non trivial task is not obvious , unless you have gone and dug into the eclipse source code. Going through the eclipse source code is not easy cause its a massive rhino . Finding the right code requires tons of patience for a newbie .

Here i am presenting a small snippet that creates a java project programatically
This code can also be found in the eclipse source tree , i am presenting here just for handy reference .

  1. Create an IProject with a name
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("dummyProject");
IProgressMonitor nullProgressMonitor = null;
project.create(nullProgressMonitor);

ResourcesPlugin is the plugin that gives us access to all the resources in eclipse including the workspace . When eclipse creates a project it shows a progress bar , we are passing null for that.

2. Open the above created java Project

IJavaProject javaProject = JavaCore.create(project)

'create' is a misonomer . This creates a decorated Java version of an eclipse project.

3. Add the java nature to the project

IProjectDescription description = project.getDescription();
description.setNatureIds(new String[]{JavaCore.NATURE_ID});
project.setDescription(description,null);

Eclipse has the concept of natures , its kinda tagging a project with java label.

4. Set the class path for the java project

IClasspathEntry[] rawClassPath = javaProject.getRawClassPath();
List classPath = new ArrayList(
Arrays.asList(rawClassPath));
classPath.add(JavaRuntime.getDefaultJREContainerEntry());
javaProject.setRawClasspath(classPath, nullProgressMonitor);

Since java and class paths are closely tied . We need to add the different class libraries to the project class path . In Eclipse every plugin has its own class loader . By adding add class libraries to the project class path we make class libraries accessible to the class loader .

5. Create the bin folder and mark it as output folder

boolean force = true;
boolean local = true;
IFolder binFolder = project.getFolder("bin");
binFolder.create(force,local,nullProgressMonitor);
IPath fullPath = binFolder.getFullPath();
javaProject.setOutputLocation(fullPath,nullProgressMonitor);

This code will create a project in the Runtime Eclipse Workbench that appears when you launch a new eclipse instance from your eclipse instance.