Archive

Posts Tagged ‘eclipse jdt’

Adding Project Nature Programmatically in Eclipse

October 17, 2012 Leave a comment

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. 🙂