DZone Forums
Go Back   DZone Forums > Community > Tools & IDEs > Eclipse
Reload this Page Load Class from project
Notices
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  (#1 (permalink)) Old
Member
 
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Jul 2009
Unhappy Load Class from project - 07-23-2009, 10:44 AM

Hello all,
i am writing an eclipse plugin and have this problem:

i want to load dynamicly a java-file from a existing/open project and create an object from it.

Code:
NietzscheClassLoader classLoader = new NietzscheClassLoader(JavaCore.create(Global.getProject()));
			Class class1 = classLoader.findClass("pac.TestFrame");
			try {
				Frame f = (Frame) class1.newInstance();
...

i use the flowing ClassLoader to do this:


Code:
package plugin.nietzsche.tools;

import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;

public class NietzscheClassLoader extends ClassLoader {
	private IJavaProject javaProject;

	public NietzscheClassLoader(IJavaProject project) {
		super();
		if (project == null || !project.exists() || !project.isOpen())
			throw new IllegalArgumentException("Invalid javaProject");
		this.javaProject = project;
	}

	public NietzscheClassLoader(IJavaProject project, ClassLoader classLoader) {
		super(classLoader);
		if (project == null || !project.exists() || !project.isOpen())
			throw new IllegalArgumentException("Invalid javaProject");
		this.javaProject = project;
	}

	@SuppressWarnings("unchecked")
	public Class findClass(String className) {
		IClassFile classFile = null;
		try {
			IType type = javaProject.findType(className);
			final IPackageFragment fragment = type.getPackageFragment();
			String java = className.substring(className.lastIndexOf('.') + 1) + ".class";
			classFile = fragment.getClassFile(java);
			final byte[] buff = classFile.getBytes();
			if (buff != null)
			return defineClass(className, buff, 0, buff.length);
		} catch (JavaModelException e) {
			System.err.println("");
			e.printStackTrace();
		}
		return null;
	}
}
now my problem:
fragment.getClassFile(java); return an *.java path and not the *.class file:

Caused by: org.eclipse.core.internal.resources.ResourceExcept ion: Resource '/test/src/pac/TestFrame.class' does not exist.
at org.eclipse.core.internal.resources.Resource.check Exists(Resource.java:310)
at org.eclipse.core.internal.resources.Resource.check Accessible(Resource.java:193)
at org.eclipse.core.internal.resources.File.getConten ts(File.java:285)
at org.eclipse.jdt.internal.core.util.Util.getResourc eContentsAsByteArray(Util.java:1005)
at org.eclipse.jdt.internal.core.ClassFile.getBytes(C lassFile.java:329)
at plugin.nietzsche.NietzscheClassLoader.findClass(Ni etzscheClassLoader.java:36)
at plugin.nietzsche.editor.NietzscheEditor.createPart Control(NietzscheEditor.java:122)
at org.eclipse.ui.internal.EditorReference.createPart Helper(EditorReference.java:661)
at org.eclipse.ui.internal.EditorReference.createPart (EditorReference.java:426)
at org.eclipse.ui.internal.WorkbenchPartReference.get Part(WorkbenchPartReference.java:592)
at org.eclipse.ui.internal.EditorReference.getEditor( EditorReference.java:263)
at org.eclipse.ui.internal.WorkbenchPage.busyOpenEdit orBatched(WorkbenchPage.java:2739)
at org.eclipse.ui.internal.WorkbenchPage.busyOpenEdit or(WorkbenchPage.java:2651)
at org.eclipse.ui.internal.WorkbenchPage.access$13(Wo rkbenchPage.java:2643)
at org.eclipse.ui.internal.WorkbenchPage$10.run(Workb enchPage.java:2595)
at org.eclipse.swt.custom.BusyIndicator.showWhile(Bus yIndicator.java:67)
at org.eclipse.ui.internal.WorkbenchPage.openEditor(W orkbenchPage.java:2590)
at org.eclipse.ui.internal.WorkbenchPage.openEditor(W orkbenchPage.java:2574)
at org.eclipse.ui.internal.WorkbenchPage.openEditor(W orkbenchPage.java:2557)
at com.placeworkers.plugin.nietzsche.views.NietzscheV iew$8.run(NietzscheView.java:306)
at org.eclipse.jface.action.Action.runWithEvent(Actio n.java:498)
at org.eclipse.jface.action.ActionContributionItem.ha ndleWidgetSelection(ActionContributionItem.java:54 6)
at org.eclipse.jface.action.ActionContributionItem.ac cess$2(ActionContributionItem.java:490)
at org.eclipse.jface.action.ActionContributionItem$6. handleEvent(ActionContributionItem.java:443)
at org.eclipse.swt.widgets.EventTable.sendEvent(Event Table.java:66)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.ja va:938)
at org.eclipse.swt.widgets.Display.runDeferredEvents( Display.java:3682)
at org.eclipse.swt.widgets.Display.readAndDispatch(Di splay.java:3293)
at org.eclipse.ui.internal.Workbench.runEventLoop(Wor kbench.java:2389)
at org.eclipse.ui.internal.Workbench.runUI(Workbench. java:2353)
at org.eclipse.ui.internal.Workbench.access$4(Workben ch.java:2219)
at org.eclipse.ui.internal.Workbench$4.run(Workbench. java:466)
at org.eclipse.core.databinding.observable.Realm.runW ithDefault(Realm.java:289)
at org.eclipse.ui.internal.Workbench.createAndRunWork bench(Workbench.java:461)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(Pl atformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplica tion.start(IDEApplication.java:106)
at org.eclipse.equinox.internal.app.EclipseAppHandle. run(EclipseAppHandle.java:169)
at org.eclipse.core.runtime.internal.adaptor.EclipseA ppLauncher.runApplication(EclipseAppLauncher.java: 106)
at org.eclipse.core.runtime.internal.adaptor.EclipseA ppLauncher.start(EclipseAppLauncher.java:76)
at org.eclipse.core.runtime.adaptor.EclipseStarter.ru n(EclipseStarter.java:363)
at org.eclipse.core.runtime.adaptor.EclipseStarter.ru n(EclipseStarter.java:176)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknow n Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Un known Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework( Main.java:508)
at org.eclipse.equinox.launcher.Main.basicRun(Main.ja va:447)
at org.eclipse.equinox.launcher.Main.run(Main.java:11 73)
at org.eclipse.equinox.launcher.Main.main(Main.java:1 148)


in this project i use the default output folder "project/bin".
Eclipse SDK Version: 3.3.2

thank you.
aroo

PS: sorry for my bad english
Reply With Quote
  (#2 (permalink)) Old
Active Contributor
 
Posts: 62
Thanks: 0
Thanked 6 Times in 6 Posts
Join Date: Jun 2009
Default 07-28-2009, 02:59 AM

The exception is caused by the TestFrame.class which is closed to generate the IClassFile, if you observe the classFile variable in your NietzscheClassLoader, you will get this TestFrame.class (not open) [in pac [in src [in test]]]
The Class maybe not in used and the class files are all output to a given folder (which could get from the IJavaProject)

If you just want to get the Object of TestFrame.class, here is one way:

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.launching.JavaRuntime;

public class NietzscheClassLoader extends ClassLoader {
private IJavaProject javaProject;
private static final String PROTOCAL_PREFIX = "file:///";

public NietzscheClassLoader(IJavaProject project) {
super();
if (project == null || !project.exists() || !project.isOpen())
throw new IllegalArgumentException("Invalid javaProject");
this.javaProject = project;
}

public Class findClass(String className) {
try {
String[] classPaths = JavaRuntime.computeDefaultRuntimeClassPath(javaPro ject);
URL[] urls = new URL[classPaths.length];
for (int i = 0; i < classPaths.length; i++)
urls[i] = new URL(PROTOCAL_PREFIX + computeForURLClassLoader(classPaths[i]));
ClassLoader loader = new URLClassLoader(urls);
Class classObject = loader.loadClass(className);
return classObject;

} catch (Exception e) {
e.printStackTrace();
}
return null;
}

private static String computeForURLClassLoader(String classpath) {
if (!classpath.endsWith("/")) {
File file = new File(classpath);
if (file.exists() && file.isDirectory())
classpath = classpath.concat("/");
}
return classpath;
}
}

BTW, I wonder your Class Global's structure,


www.eclaxy.com
let's perfect the eclipse!
Reply With Quote
Reply

Tags
classloader, eclipse, plugin

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Execute/debug given class from a project. DanielKec NetBeans 0 01-16-2009 07:44 AM
copy only the changed class files in a java project ms74120 Eclipse 0 06-04-2008 07:11 PM
Application fails on Mac - can't load application class kam_83 Eclipse 0 05-02-2008 10:21 AM
uml2 load uml eldjon Eclipse 0 03-17-2008 01:02 PM
EMF load XMI eldjon Eclipse 1 02-29-2008 05:12 AM


Copyright 1997-2009, DZone, Inc.
vBulletin Skin developed by: vBStyles.com