List of usage examples for java.net URLClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:cz.muni.fi.mir.services.MathCanonicalizerLoaderImpl.java
@Override public void execute(List<Formula> formulas, ApplicationRun applicationRun) throws IllegalStateException { if (!fileService.canonicalizerExists(applicationRun.getRevision().getRevisionHash())) { throw new IllegalStateException("Given canonicalizer with revision [" + applicationRun.getRevision().getRevisionHash() + "] does not exists."); } else {//from w w w . j a va 2 s. c om Path path = FileSystems.getDefault().getPath(this.jarFolder, applicationRun.getRevision().getRevisionHash() + ".jar"); Class mainClass = null; URL jarFile = null; try { jarFile = path.toUri().toURL(); } catch (MalformedURLException me) { logger.fatal(me); } URLClassLoader cl = URLClassLoader.newInstance(new URL[] { jarFile }); try { mainClass = cl.loadClass("cz.muni.fi.mir.mathmlcanonicalization." + this.mainClassName); } catch (ClassNotFoundException cnfe) { logger.fatal(cnfe); } CanonicalizationTask ct = taskFactory.createTask(); ct.setDependencies(formulas, applicationRun, mainClass); taskService.submitTask(ct); } }
From source file:org.b3log.latke.plugin.PluginManager.java
/** * Registers event listeners with the specified plugin properties, class * loader and plugin./* ww w. j a v a2 s . co m*/ * * <p> * <b>Note</b>: If the specified plugin has some event listeners, each * of these listener MUST implement a static method named * {@code getInstance} to obtain an instance of this listener. See * <a href="http://en.wikipedia.org/wiki/Singleton_pattern"> * Singleton Pattern</a> for more details. * </p> * * @param props the specified plugin properties * @param classLoader the specified class loader * @param plugin the specified plugin * @throws Exception exception */ private static void registerEventListeners(final Properties props, final URLClassLoader classLoader, final AbstractPlugin plugin) throws Exception { final String eventListenerClasses = props.getProperty(Plugin.PLUGIN_EVENT_LISTENER_CLASSES); final String[] eventListenerClassArray = eventListenerClasses.split(","); for (int i = 0; i < eventListenerClassArray.length; i++) { final String eventListenerClassName = eventListenerClassArray[i]; if (Strings.isEmptyOrNull(eventListenerClassName)) { LOGGER.log(Level.INFO, "No event listener to load for plugin[name={0}]", plugin.getName()); return; } LOGGER.log(Level.FINER, "Loading event listener[className={0}]", eventListenerClassName); final Class<?> eventListenerClass = classLoader.loadClass(eventListenerClassName); final Method getInstance = eventListenerClass.getMethod("getInstance"); final AbstractEventListener<?> eventListener = (AbstractEventListener) getInstance .invoke(eventListenerClass); final EventManager eventManager = EventManager.getInstance(); eventManager.registerListener(eventListener); LOGGER.log(Level.FINER, "Registered event listener[class={0}, eventType={1}] for plugin[name={2}]", new Object[] { eventListener.getClass(), eventListener.getEventType(), plugin.getName() }); } }
From source file:solidbase.Main.java
/** * Reload SolidBase with an extended classpath. Calls {@link #pass2(String...)} when it's done. * * @param args The arguments from the command line. * @param jars The jars that need to be added to the classpath. * @param verbose Show more information. * @throws SQLExecutionException When an {@link SQLException} is thrown during execution of a database change. *//*from w w w.ja v a2 s .c om*/ static protected void reload(String[] args, List<String> jars, boolean verbose) throws SQLExecutionException { if (jars == null || jars.isEmpty()) { // No need to add a new classloader pass2(args); return; } if (verbose) console.println("Extending classpath"); // Add the driver jar(s) to the classpath URLClassLoader classLoader = (URLClassLoader) Main.class.getClassLoader(); URL[] orig = classLoader.getURLs(); URL[] urls; urls = new URL[orig.length + jars.size()]; System.arraycopy(orig, 0, urls, 0, orig.length); int i = orig.length; for (String jar : jars) { File driverJarFile = new File(jar); try { urls[i++] = driverJarFile.toURI().toURL(); } catch (MalformedURLException e) { throw new SystemException(e); } if (verbose) console.println("Adding jar to classpath: " + urls[i - 1]); } if (verbose) console.println(); // Create a new classloader with the new classpath classLoader = new URLClassLoader(urls, Main.class.getClassLoader().getParent()); // Execute the main class through the new classloader with reflection Class<?> main; try { main = classLoader.loadClass("solidbase.Main"); } catch (ClassNotFoundException e) { throw new SystemException(e); } Method method; try { method = main.getDeclaredMethod("pass2", String[].class); } catch (SecurityException e) { throw new SystemException(e); } catch (NoSuchMethodException e) { throw new SystemException(e); } // TODO Should we change the contextClassLoader too? try { method.invoke(method, (Object) args); } catch (IllegalArgumentException e) { throw new SystemException(e); } catch (IllegalAccessException e) { throw new SystemException(e); } catch (InvocationTargetException e) { throw new SystemException(e.getCause()); } }
From source file:ezbake.thriftrunner.starters.SimpleStarter.java
@SuppressWarnings("unchecked") @Override//from w ww. j ava 2 s. com public Class<? extends EzBakeBaseThriftService> getServiceClass(URLClassLoader loader) throws Exception { if (!Strings.isNullOrEmpty(className)) { return (Class<? extends EzBakeBaseThriftService>) loader.loadClass(className); } else { return getServiceClassUsingReflectionFromJar(loader); } }
From source file:com.heimuheimu.runningtask.task.service.support.SimpleTaskExecutor.java
private synchronized boolean executeStaticMethod(String className, String methodName, URLClassLoader classLoader) { long startTime = System.currentTimeMillis(); try {// w w w . j a va 2 s. c om Class<?> clz = classLoader.loadClass(className); Method method = clz.getMethod(methodName); method.invoke(null); LOG.info("Execute `{}#{}()` success. Cost: `{}ms`", new Object[] { className, methodName, System.currentTimeMillis() - startTime }); return true; } catch (Exception e) { LOG.error("Execute `" + className + "#" + methodName + "()` fail. Cost: `" + (System.currentTimeMillis() - startTime) + "ms`", e); return false; } }
From source file:me.jaimegarza.syntax.test.java.TestJavaLexerModes.java
@Test public void testJavaLexerModes() throws ParsingException, AnalysisException, OutputException, MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { generateLanguageFile(args);// www . jav a 2 s . com File source = new File(tmpLanguageFile); File sourceDir = source.getParentFile(); CompilationResult result = compileJavaFile(source, sourceDir); if (result.getErrors().length > 0) { for (CompilationProblem problemo : result.getErrors()) { if (problemo.isError()) { System.err.println(problemo.toString()); } } Assert.fail("Errors during the compilation of the output java file"); } URL urls[] = new URL[1]; urls[0] = sourceDir.toURI().toURL(); URLClassLoader classLoader = URLClassLoader.newInstance(urls, this.getClass().getClassLoader()); String className = FilenameUtils.getBaseName(tmpLanguageFile); Class<?> clazz = classLoader.loadClass(className); Object parser = clazz.newInstance(); //Method setVerbose = parser.getClass().getMethod("setVerbose", boolean.class); Method parse = parser.getClass().getMethod("parse"); Method getOutput = parser.getClass().getMethod("getOutput"); //setVerbose.invoke(parser, true); Object o = parse.invoke(parser); Assert.assertTrue(o instanceof Integer); int rc = (Integer) o; Assert.assertEquals(rc, 1, "Parse did not succeed"); o = getOutput.invoke(parser); Assert.assertTrue(o instanceof String); String s = (String) o; Assert.assertEquals(s, "bacaab", "string does not match"); }
From source file:me.jaimegarza.syntax.test.java.TestJavaRegexTokenizer.java
@Test public void test01WithExecute() throws ParsingException, AnalysisException, OutputException, MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { generateLanguageFile(expandedArgs);//from ww w. jav a2 s . c o m File source = new File(tmpLanguageFile); File sourceDir = source.getParentFile(); CompilationResult result = compileJavaFile(source, sourceDir); if (result.getErrors().length > 0) { for (CompilationProblem cr : result.getErrors()) { System.err.println(cr); } } Assert.assertEquals(result.getErrors().length, 0, "Syntax errors found trying to execute"); URL urls[] = new URL[1]; urls[0] = sourceDir.toURI().toURL(); URLClassLoader classLoader = URLClassLoader.newInstance(urls, this.getClass().getClassLoader()); String className = FilenameUtils.getBaseName(tmpLanguageFile); Class<?> clazz = classLoader.loadClass(className); Object parser = clazz.newInstance(); //Method setVerbose = parser.getClass().getMethod("setVerbose", boolean.class); Method parse = parser.getClass().getMethod("parse"); Method getExpr = parser.getClass().getMethod("getExpr"); //setVerbose.invoke(parser, true); Object o = parse.invoke(parser); Assert.assertTrue(o instanceof Integer); int rc = (Integer) o; Assert.assertEquals(rc, 1, "Parse did not succeed"); o = getExpr.invoke(parser); Assert.assertTrue(o instanceof String); String s = (String) o; Assert.assertEquals(s, "EABCDFGIA", "string does not match"); }
From source file:me.jaimegarza.syntax.test.java.TestLalr.java
@Test public void test01WithExecute() throws ParsingException, AnalysisException, OutputException, MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { generateLanguageFile(expandedArgs);/*from ww w . j a v a 2s . c o m*/ File source = new File(tmpLanguageFile); File sourceDir = source.getParentFile(); CompilationResult result = compileJavaFile(source, sourceDir); if (result.getErrors().length > 0) { for (CompilationProblem cr : result.getErrors()) { System.err.println(cr); } } Assert.assertEquals(result.getErrors().length, 0, "Syntax errors found trying to execute"); URL urls[] = new URL[1]; urls[0] = sourceDir.toURI().toURL(); URLClassLoader classLoader = URLClassLoader.newInstance(urls, this.getClass().getClassLoader()); String className = FilenameUtils.getBaseName(tmpLanguageFile); Class<?> clazz = classLoader.loadClass(className); Object parser = clazz.newInstance(); Method setVerbose = parser.getClass().getMethod("setVerbose", boolean.class); Method parse = parser.getClass().getMethod("parse"); Method getExpr = parser.getClass().getMethod("getExpr"); setVerbose.invoke(parser, true); Object o = parse.invoke(parser); Assert.assertTrue(o instanceof Integer); int rc = (Integer) o; Assert.assertEquals(rc, 1, "Parse did not succeed"); o = getExpr.invoke(parser); Assert.assertTrue(o instanceof String); String s = (String) o; Assert.assertEquals(s, "(abc)d", "string does not match"); }
From source file:org.deventropy.shared.utils.ClassUtilTest.java
@Test public void testCallerClassloader() throws Exception { // Write the source file - see // http://stackoverflow.com/questions/2946338/how-do-i-programmatically-compile-and-instantiate-a-java-class final File sourceFolder = workingFolder.newFolder(); // Prepare source somehow. final String source = "package test; public class Test { }"; // Save source in .java file. final File sourceFile = new File(sourceFolder, "test/Test.java"); sourceFile.getParentFile().mkdirs(); FileUtils.writeStringToFile(sourceFile, source, "UTF-8"); // Compile the file final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); final Iterable<? extends JavaFileObject> compilationUnit = fileManager .getJavaFileObjectsFromFiles(Arrays.asList(sourceFile)); compiler.getTask(null, fileManager, null, null, null, compilationUnit).call(); // Create the class loader final URLClassLoader urlcl = new URLClassLoader(new URL[] { sourceFolder.toURI().toURL() }); final Class<?> loadedClass = urlcl.loadClass("test.Test"); final ContextClNullingObject testObj = new ContextClNullingObject(loadedClass.newInstance()); final Thread worker = new Thread(testObj); worker.start();/* www. j a va2 s . c om*/ worker.join(); assertEquals(urlcl, testObj.getReturnedCl()); urlcl.close(); }
From source file:com.googlecode.dex2jar.tools.DecryptStringCmd.java
@Override protected void doCommandLine() throws Exception { if (remainingArgs.length != 1) { usage();/*from w w w . j a v a 2 s . c o m*/ return; } File jar = new File(remainingArgs[0]); if (!jar.exists()) { System.err.println(jar + " is not exists"); return; } if (methodName == null || methodOwner == null) { System.err.println("Please set --decrypt-method-owner and --decrypt-method-name"); return; } if (output == null) { if (jar.isDirectory()) { output = new File(jar.getName() + "-decrypted.jar"); } else { output = new File(FilenameUtils.getBaseName(jar.getName()) + "-decrypted.jar"); } } if (output.exists() && !forceOverwrite) { System.err.println(output + " exists, use --force to overwrite"); return; } System.err.println(jar + " -> " + output); List<String> list = new ArrayList<String>(); if (classpath != null) { list.addAll(Arrays.asList(classpath.split(";|:"))); } list.add(jar.getAbsolutePath()); URL[] urls = new URL[list.size()]; for (int i = 0; i < list.size(); i++) { urls[i] = new File(list.get(i)).toURI().toURL(); } final Method jmethod; final String targetMethodDesc; try { Class<?> argType = "string".equals(type) ? String.class : int.class; URLClassLoader cl = new URLClassLoader(urls); jmethod = cl.loadClass(methodOwner).getDeclaredMethod(methodName, argType); jmethod.setAccessible(true); targetMethodDesc = Type.getMethodDescriptor(jmethod); } catch (Exception ex) { System.err.println("can't load method: String " + methodOwner + "." + methodName + "(" + type + ")"); ex.printStackTrace(); return; } final String methodOwnerInternalType = this.methodOwner.replace('.', '/'); final OutHandler fo = FileOut.create(output, true); try { new FileWalker().withStreamHandler(new StreamHandler() { @Override public void handle(boolean isDir, String name, StreamOpener current, Object nameObject) throws IOException { if (isDir || !name.endsWith(".class")) { fo.write(isDir, name, current == null ? null : current.get(), nameObject); return; } ClassReader cr = new ClassReader(current.get()); ClassNode cn = new ClassNode(); cr.accept(cn, ClassReader.EXPAND_FRAMES); for (Object m0 : cn.methods) { MethodNode m = (MethodNode) m0; if (m.instructions == null) { continue; } AbstractInsnNode p = m.instructions.getFirst(); while (p != null) { if (p.getOpcode() == Opcodes.INVOKESTATIC) { MethodInsnNode mn = (MethodInsnNode) p; if (mn.name.equals(methodName) && mn.desc.equals(targetMethodDesc) && mn.owner.equals(methodOwnerInternalType)) { AbstractInsnNode q = p.getPrevious(); AbstractInsnNode next = p.getNext(); if (q.getOpcode() == Opcodes.LDC) { LdcInsnNode ldc = (LdcInsnNode) q; tryReplace(m.instructions, p, q, jmethod, ldc.cst); } else if (q.getType() == AbstractInsnNode.INT_INSN) { IntInsnNode in = (IntInsnNode) q; tryReplace(m.instructions, p, q, jmethod, in.operand); } else { switch (q.getOpcode()) { case Opcodes.ICONST_M1: case Opcodes.ICONST_0: case Opcodes.ICONST_1: case Opcodes.ICONST_2: case Opcodes.ICONST_3: case Opcodes.ICONST_4: case Opcodes.ICONST_5: int x = ((InsnNode) q).getOpcode() - Opcodes.ICONST_0; tryReplace(m.instructions, p, q, jmethod, x); break; } } p = next; continue; } } p = p.getNext(); } } ClassWriter cw = new ClassWriter(0); cn.accept(cw); fo.write(false, cr.getClassName() + ".class", cw.toByteArray(), null); } }).walk(jar); } finally { IOUtils.closeQuietly(fo); } }