| ClassLoader from a JavaProject [message #225519] |
Wed, 08 March 2006 01:16  |
Eclipse User |
|
|
|
Dear All,
Did anyone know how can I get a ClassLoader which based on the
classpath entries of a single java project? Did JDT Plugin provide this
class loader already or need to do it by myself? Thanks.
Best Regards,
Eddie
|
|
|
|
| Re: ClassLoader from a JavaProject [message #225645 is a reply to message #225519] |
Thu, 09 March 2006 05:33  |
Eclipse User |
|
|
|
Originally posted by: luca.none.net
"eddie" <superman_eddie@yahoo.com.hk> ha scritto nel messaggio
news:dulssq$d7o$1@eclipse.org...
> Dear All,
>
> Did anyone know how can I get a ClassLoader which based on the
> classpath entries of a single java project? Did JDT Plugin provide this
> class loader already or need to do it by myself? Thanks.
>
I had the same problem some time ago. This is how I solved it. It's kind of
tricky, but it gets the job done.
You first have to get the ResolvedClassPath from the project which gives you
everything inside of the project classpath, then you have to add the default
output location of the project, i.e. the bin directory.
When you have all the entries a new URLClassLoader, using the actual class
loader as parent.
Hope this helps,
bye
public static ClassLoader geProjectLoader(IJavaProject javaProject) throws
Exception
{
IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
String wsPath = javaProject.getProject().getLocation().toPortableString();
String firstEntryLocation = javaProject.getPath().toPortableString();
int idx = wsPath.indexOf(firstEntryLocation);
wsPath = wsPath.substring(0,idx);
String fullPath = null;
URL[] urls = new URL[entries.length+1];
int i = 0;
urls[i++] = new File(wsPath +
javaProject.getOutputLocation().toPortableString()).toURL();
for (IClasspathEntry entry : entries)
{
if(entry.getEntryKind() == IClasspathEntry.CPE_PROJECT)
{
IResource project =
ResourcesPlugin.getWorkspace().getRoot().findMember(entry.ge tPath());
String projectPath =
JavaCore.create(project.getProject()).getOutputLocation().to PortableString();
fullPath = wsPath + projectPath;
}
else
{
Object resource =
JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot() ,entry.getPath(),true);
if (resource instanceof IResource)
{
IResource iFile = (IResource) resource;
fullPath = iFile.getLocation().toPortableString();
}
else if (resource instanceof File)
{
File file = (File) resource;
fullPath = file.getAbsolutePath();
}
}
urls[i++] = new File(fullPath).toURL();
}
URLClassLoader classLoader = new
URLClassLoader(urls,String.class.getClassLoader());
return classLoader;
}
|
|
|
Powered by
FUDForum. Page generated in 0.03722 seconds