How to programatically add classpaths to an eclipse project

This is very easy, All you need is the name of the project or IProject it self and the jar path list.

   public static void setClassPathToNewLibs(String projectName,String[] jarPathList){
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
        try {
            IJavaProject javaProject = (IJavaProject)project.getNature(JavaCore.NATURE_ID);
            IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
            List list = new LinkedList(java.util.Arrays.asList(rawClasspath));
            for(String path:jarPathList){
                String jarPath = path.toString();
                boolean isAlreadyAdded=false;
                for(IClasspathEntry cpe:rawClasspath){
                    isAlreadyAdded=cpe.getPath().toOSString().equals(jarPath);
                    if (isAlreadyAdded) break;
                }
                if (!isAlreadyAdded){
                    IClasspathEntry jarEntry = JavaCore.newLibraryEntry(new Path(jarPath),null,null);
                    list.add(jarEntry);
                }
            }
            IClasspathEntry[] newClasspath = (IClasspathEntry[])list.toArray(new IClasspathEntry[0]);
            javaProject.setRawClasspath(newClasspath,null);
        } catch (CoreException e) {
            e.printStackTrace();
        }

}

Should work for any kind of eclipse project I guess.

Tags: ,

One Response to “How to programatically add classpaths to an eclipse project”

  1. Peeyush Bhadola Says:

    Thanks you so much. It worked for the Dynamic Web project.

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: