Home > eclipse jdt, eclipse rcp > Adding Project Nature Programmatically in Eclipse

Adding Project Nature Programmatically in Eclipse

In this post we are going to see how can we add a custom project nature programmatically.

I found a nice post

which precisely tells us how should we create a java project programmatically. Now what if I want to have a custom project nature for my project?

Every project created inside eclipse will be associated with natures.
You can find this in the .project file. An example is shown below.

Now in sometimes , we may require to add custom nature to our project. The extension point org.eclipse.core.resources.natures helps us to do that.

Add org.eclipse.core.resources as a dependency in plugin.xml.
Then add org.eclipse.core.resources.natures extension point. It may look like below


<extension
         id="myplugin.myprojnature"
         point="org.eclipse.core.resources.natures">
      <runtime>
         <run
               class="myplugin.MyProjNature">
         </run>
      </runtime>
 </extension>

Now , create a MyProjNature class which implements IProjectNature interface.


public class MyProjNature implements IProjectNature {

	public static final String NATURE_ID = "com.mycomp.myproject.myprojnature";
	
	@Override
	public void configure() throws CoreException {
		// TODO Auto-generated method stub

	}

	@Override
	public void deconfigure() throws CoreException {
		// TODO Auto-generated method stub

	}

	@Override
	public IProject getProject() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setProject(IProject arg0) {
		// TODO Auto-generated method stub

	}

}

The below piece of code will do the job of adding the custom nature,


             try {
			IProjectDescription desc = myProj.getDescription();
			String[] prevNatures = desc.getNatureIds();
			String[] newNatures = new String[prevNatures.length + 1];
			System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
			newNatures[prevNatures.length] = MyProjNature.NATURE_ID;
			desc.setNatureIds(newNatures);
			myProj.setDescription(desc, new NullProgessMonitor());
		} catch (CoreException e) {
			e.printStackTrace();
		}

That’s it. Hope this is helpful.
Happy coding. 🙂

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: