Programmatically add source folder from Eclipse plugin
Asked Answered
I

2

7

I am developing m2e connector for out maven plugin, which actually generates some sources. I need to add generated sources(folder) to workspace as source folder.

I used JavaCore for edit .classpath file:

    IJavaProject javaProject = JavaCore.create(proj);
    IClasspathEntry[] entries = javaProject.getRawClasspath();

    IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];
    System.arraycopy(entries, 0, newEntries, 0, entries.length);

    Path myPath = new Path("target/generated-sources");
    IClasspathEntry myEntry = JavaCore.newSourceEntry(myPath);

    newEntries[entries.length] = JavaCore.newSourceEntry(myEntry.getPath());
    javaProject.setRawClasspath(newEntries, null);

But this code doesn't work it says: Path for IClasspathEntry must be absolute

If I tried to use absolute path, it has been written to .classpath but in eclipse it wasn't displayed as source folder.

Have anyone any suggestion? It should be easy task but I cannot figure out how to solve it.

Insuperable answered 3/11, 2011 at 11:7 Comment(0)
I
7

Problem solved...it was easier then I expected...

IJavaProject javaProject = JavaCore.create(proj);
IClasspathEntry[] entries = javaProject.getRawClasspath();

IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];
System.arraycopy(entries, 0, newEntries, 0, entries.length);

IPath srcPath= javaProject.getPath().append("target/generated-sources");
IClasspathEntry srcEntry= JavaCore.newSourceEntry(srcPath, null);

newEntries[entries.length] = JavaCore.newSourceEntry(srcEntry.getPath());
javaProject.setRawClasspath(newEntries, null);

And this will add source entry to .classpath file:

Insuperable answered 9/11, 2011 at 8:55 Comment(1)
Thank you mister! While I can't try it out at the moment, I'll hopefully be able to use this information tomorrow. You might have saved me a great deal of headache given the poor documentation there is about the issue.Catie
I
0

Try one of JavaCore.newSourceEntry(...) methods instead of JavaCore.newProjectEntry(...).

Ishmul answered 3/11, 2011 at 15:11 Comment(1)
my mistake...I wrote bad code. I tried JavaCore.newProjectEntry(...) and there was exception: Path for IClasspathEntry must be absoluteMerodach

© 2022 - 2024 — McMap. All rights reserved.