Java tutorial
/** * */ package mt.com.southedge.jclockwork.plugin.classloader; /* ****************************************************************************** * Copyright (c) 2011 SouthEdge Software and Consultancy. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Carl Frendo - initial design and implementation * ******************************************************************************/ import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.internal.core.JavaProject; /** * * @author cfrendo * */ public class JClockWorkClassLoader { private static JClockWorkClassLoader jClockWorkClassLoader; private JClockWorkClassLoader() { } public static JClockWorkClassLoader getInstance() { if (jClockWorkClassLoader == null) { jClockWorkClassLoader = new JClockWorkClassLoader(); } return jClockWorkClassLoader; } /** * Creates a class loader including the classes found in the java project. Also adds the binary location to the * created class loader. * * @param jp the java project * @return a class loader. * @throws CoreException core exception. */ public ClassLoader createClassLoader(IJavaProject jp) throws CoreException { IClasspathEntry[] javacp = jp.getResolvedClasspath(false); URL[] url = new URL[javacp.length + 1]; // Need also to add binary location for (int i = 0; i < javacp.length; i++) { try { IPath path = javacp[i].getPath(); IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path); if (resource != null) { path = resource.getLocation(); } url[i] = path.toFile().getAbsoluteFile().toURL(); } catch (MalformedURLException e) { continue; } } IPath binPath = jp.getOutputLocation(); binPath = ResourcesPlugin.getWorkspace().getRoot().findMember(binPath).getLocation(); try { url[url.length - 1] = binPath.toFile().toURL(); } catch (MalformedURLException e) { // Should not happen. e.printStackTrace(); } return new URLClassLoader(url); } public ClassLoader createClassLoader(IProject project) throws CoreException { return createClassLoader(new JavaProject(project, null)); } }