Search Engine

Saturday, July 10, 2010

Creating new Java elements via the Java model

The following will create a command which will create a new package to existing (and open) Java projects which have the same name as the Java project. For example if you have a project "de.vogella.test" in your workspace without any package this command will create the package "de.vogella.test" in this project.

Create a new plugin project "de.vogella.jdt.newelements".

Add a new command "de.vogella.jdt.newelements.AddPackage" and put it into the menu.

Create the following handler for this command.

package de.vogella.jdt.newelements.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;

public class AddPackage extends AbstractHandler implements IHandler {

public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
// Get all projects in the workspace
IProject[] projects = root.getProjects();
// Loop over all projects
for (IProject project : projects) {
try {
// Only work on open projects with the Java nature
if (project.isOpen()
&& project
.isNatureEnabled("org.eclipse.jdt.core.javanature")) {
IJavaProject javaProject = JavaCore.create(project);
IFolder folder = project.getFolder("src");
// folder.create(true, true, null);
IPackageFragmentRoot srcFolder = javaProject
IPackageFragment fragment = srcFolder
.createPackageFragment(project.getName(), true,
} catch (CoreException e) {
return null;



Post a Comment