java.net.URLClassLoader Java Examples
The following examples show how to use
java.net.URLClassLoader.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReflectionBenchmarkUniqueAccessTest.java From AVM with MIT License | 7 votes |
private long uniqueInstanceMethodHandleInstanceFieldReadAccessInvokeExactOnly(int spins) throws Throwable { ReflectionTarget[] targets = new ReflectionTarget[spins]; MethodHandle[] fields = new MethodHandle[spins]; for (int i = 0; i < spins; i++) { ClassLoader loader = new URLClassLoader(new URL[]{ classpathDirectory.toURI().toURL() }); Class<?> clazz = loader.loadClass(targetClassName); targets[i] = (ReflectionTarget) MethodHandles.lookup().findConstructor(clazz, MethodType.methodType(void.class)).invoke(); fields[i] = MethodHandles.lookup().findGetter(clazz, instanceField, Object.class); } long start = System.nanoTime(); for (int i = 0; i < spins; i++) { Object o = fields[i].invokeExact(targets[i]); } long end = System.nanoTime(); return end - start; }
Example #2
Source File: AvailableGames.java From triplea with GNU General Public License v3.0 | 6 votes |
private static Map<String, URI> getGamesFromZip(final File map) { final Map<String, URI> availableGames = new HashMap<>(); try (InputStream fis = new FileInputStream(map); ZipInputStream zis = new ZipInputStream(fis); URLClassLoader loader = new URLClassLoader(new URL[] {map.toURI().toURL()})) { ZipEntry entry = zis.getNextEntry(); while (entry != null) { if (entry.getName().contains("games/") && entry.getName().toLowerCase().endsWith(".xml")) { final URL url = loader.getResource(entry.getName()); if (url != null) { availableGames.putAll( getAvailableGames(URI.create(url.toString().replace(" ", "%20")))); } } // we have to close the loader to allow files to be deleted on windows zis.closeEntry(); entry = zis.getNextEntry(); } } catch (final IOException e) { log.log(Level.SEVERE, "Error reading zip file in: " + map.getAbsolutePath(), e); } return availableGames; }
Example #3
Source File: Main.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
private ContentSigner loadSigningMechanism(String signerClassName, String signerClassPath) throws Exception { // construct class loader String cpString = null; // make sure env.class.path defaults to dot // do prepends to get correct ordering cpString = PathList.appendPath(System.getProperty("env.class.path"), cpString); cpString = PathList.appendPath(System.getProperty("java.class.path"), cpString); cpString = PathList.appendPath(signerClassPath, cpString); URL[] urls = PathList.pathToURLs(cpString); ClassLoader appClassLoader = new URLClassLoader(urls); // attempt to find signer Class<?> signerClass = appClassLoader.loadClass(signerClassName); // Check that it implements ContentSigner Object signer = signerClass.newInstance(); if (!(signer instanceof ContentSigner)) { MessageFormat form = new MessageFormat( rb.getString("signerClass.is.not.a.signing.mechanism")); Object[] source = {signerClass.getName()}; throw new IllegalArgumentException(form.format(source)); } return (ContentSigner)signer; }
Example #4
Source File: SchemaGenerator.java From hottub with GNU General Public License v2.0 | 6 votes |
private static String setClasspath(String givenClasspath) { StringBuilder cp = new StringBuilder(); appendPath(cp, givenClasspath); ClassLoader cl = Thread.currentThread().getContextClassLoader(); while (cl != null) { if (cl instanceof URLClassLoader) { for (URL url : ((URLClassLoader) cl).getURLs()) { appendPath(cp, url.getPath()); } } cl = cl.getParent(); } appendPath(cp, findJaxbApiJar()); return cp.toString(); }
Example #5
Source File: AbstractTest.java From gridgo with MIT License | 6 votes |
public void init() throws Exception { System.out.println("init..."); // Provide the URL corresponding to the folder that contains the class // `javassist.MyClass` this.cl = new URLClassLoader(new URL[] { new File("target/classes").toURI().toURL(), new File("target/test-classes").toURI().toURL() }) { protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { try { // Try to find the class for this CL return findClass(name); } catch (ClassNotFoundException e) { // Could not find the class so load it from the parent return super.loadClass(name, resolve); } } }; // Get the current context CL and store it into old this.old = Thread.currentThread().getContextClassLoader(); // Set the custom CL as new context CL Thread.currentThread().setContextClassLoader(cl); }
Example #6
Source File: JAXRSContainerTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testOnewayMethod() throws Exception { JAXRSContainer container = new JAXRSContainer(null); final String onewayMethod = "deleteRepository"; ToolContext context = new ToolContext(); context.put(WadlToolConstants.CFG_OUTPUTDIR, output.getCanonicalPath()); context.put(WadlToolConstants.CFG_WADLURL, getLocation("/wadl/test.xml")); context.put(WadlToolConstants.CFG_COMPILE, "true"); context.put(WadlToolConstants.CFG_ONEWAY, onewayMethod); container.setContext(context); container.execute(); assertNotNull(output.list()); ClassCollector cc = context.get(ClassCollector.class); assertEquals(1, cc.getServiceClassNames().size()); try (URLClassLoader loader = new URLClassLoader(new URL[]{output.toURI().toURL()})) { final Class<?> generatedClass = loader.loadClass(cc.getServiceClassNames().values().iterator().next()); Method m = generatedClass.getMethod(onewayMethod, String.class); assertNotNull(m.getAnnotation(Oneway.class)); } }
Example #7
Source File: PackageInfoCache.java From j2cl with Apache License 2.0 | 6 votes |
public static void init(List<String> classPathEntries, Problems problems) { checkState( packageInfoCacheStorage.get() == null, "PackageInfoCache should only be initialized once per thread."); // Constructs a URLClassLoader to do the dirty work of finding package-info.class files in the // classpath of the compile. List<URL> classPathUrls = new ArrayList<>(); for (String classPathEntry : classPathEntries) { try { classPathUrls.add(new URL("file:" + classPathEntry)); } catch (MalformedURLException e) { problems.fatal(FatalError.CANNOT_OPEN_FILE, e.toString()); } } URLClassLoader resourcesClassLoader = new URLClassLoader( Iterables.toArray(classPathUrls, URL.class), PackageInfoCache.class.getClassLoader()); packageInfoCacheStorage.set(new PackageInfoCache(resourcesClassLoader, problems)); }
Example #8
Source File: TestTezClientUtils.java From incubator-tez with Apache License 2.0 | 6 votes |
/** * * @throws Exception */ @Test (timeout=5000) public void validateSetTezJarLocalResourcesDefinedExistingDirectoryIgnored() throws Exception { URL[] cp = ((URLClassLoader)ClassLoader.getSystemClassLoader()).getURLs(); StringBuffer buffer = new StringBuffer(); for (URL url : cp) { buffer.append(url.toExternalForm()); buffer.append(","); } TezConfiguration conf = new TezConfiguration(); conf.set(TezConfiguration.TEZ_LIB_URIS, buffer.toString()); conf.setBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, true); Credentials credentials = new Credentials(); Map<String, LocalResource> localizedMap = TezClientUtils.setupTezJarsLocalResources(conf, credentials); assertTrue(localizedMap.isEmpty()); }
Example #9
Source File: AllocationStackTrace.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Imitates class loading. Each invocation of this method causes a new class * loader object is created and a new class is loaded by this class loader. * Method throws OOM when run out of memory. */ static protected void loadNewClass() { try { String jarUrl = "file:" + (counter++) + ".jar"; URL[] urls = new URL[]{new URL(jarUrl)}; URLClassLoader cl = new URLClassLoader(urls); Proxy.newProxyInstance( cl, new Class[]{Foo.class}, new FooInvocationHandler(new FooBar())); } catch (java.net.MalformedURLException badThing) { // should never occur System.err.println("Unexpected error: " + badThing); throw new RuntimeException(badThing); } }
Example #10
Source File: ChangeSetTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testCustomClassLoader() throws Exception { // JBRULES-3630 String absolutePath = new File("file").getAbsolutePath(); URL url = ChangeSetTest.class.getResource(ChangeSetTest.class.getSimpleName() + ".class"); AtomicReference<File> jar = new AtomicReference<>(); assertTimeoutPreemptively(Duration.ofSeconds(10), () -> { File file = new File( url.toURI() ); while ( true ) { file = file.getParentFile(); File j = new File( file, "/src/test/resources/org/drools/compiler/compiler/xml/changeset/changeset.jar" ); if ( j.exists() ) { jar.set(j); break; } } }, "JAR not found in time."); ClassLoader classLoader = URLClassLoader.newInstance(new URL[]{jar.get().toURI().toURL()}, getClass().getClassLoader()); Resource changeSet = ResourceFactory.newClassPathResource("changeset1.xml", classLoader); KnowledgeBuilderConfiguration conf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(null, classLoader); KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder(conf); builder.add(changeSet, ResourceType.CHANGE_SET); }
Example #11
Source File: B7050028.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection(); int len = conn.getContentLength(); byte[] data = new byte[len]; InputStream is = conn.getInputStream(); is.read(data); is.close(); conn.setDefaultUseCaches(false); File jar = File.createTempFile("B7050028", ".jar"); jar.deleteOnExit(); OutputStream os = new FileOutputStream(jar); ZipOutputStream zos = new ZipOutputStream(os); ZipEntry ze = new ZipEntry("B7050028.class"); ze.setMethod(ZipEntry.STORED); ze.setSize(len); CRC32 crc = new CRC32(); crc.update(data); ze.setCrc(crc.getValue()); zos.putNextEntry(ze); zos.write(data, 0, len); zos.closeEntry(); zos.finish(); zos.close(); os.close(); System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName())); }
Example #12
Source File: Loader.java From IoTgo_Android_App with MIT License | 6 votes |
/** * Generate the classpath (as a string) of all classloaders * above the given classloader. * * This is primarily used for jasper. * @return the system class path */ public static String getClassPath(ClassLoader loader) throws Exception { StringBuilder classpath=new StringBuilder(); while (loader != null && (loader instanceof URLClassLoader)) { URL[] urls = ((URLClassLoader)loader).getURLs(); if (urls != null) { for (int i=0;i<urls.length;i++) { Resource resource = Resource.newResource(urls[i]); File file=resource.getFile(); if (file!=null && file.exists()) { if (classpath.length()>0) classpath.append(File.pathSeparatorChar); classpath.append(file.getAbsolutePath()); } } } loader = loader.getParent(); } return classpath.toString(); }
Example #13
Source File: PinotServiceManagerAdminApiApplication.java From incubator-pinot with Apache License 2.0 | 6 votes |
private void setupSwagger() { BeanConfig beanConfig = new BeanConfig(); beanConfig.setTitle("Pinot Starter API"); beanConfig.setDescription("APIs for accessing Pinot Starter information"); beanConfig.setContact("https://github.com/apache/incubator-pinot"); beanConfig.setVersion("1.0"); beanConfig.setSchemes(new String[]{"http"}); beanConfig.setBasePath(_baseUri.getPath()); beanConfig.setResourcePackage(RESOURCE_PACKAGE); beanConfig.setScan(true); HttpHandler httpHandler = new CLStaticHttpHandler(PinotServiceManagerAdminApiApplication.class.getClassLoader(), "/api/"); // map both /api and /help to swagger docs. /api because it looks nice. /help for backward compatibility _httpServer.getServerConfiguration().addHttpHandler(httpHandler, "/api/", "/help/"); URL swaggerDistLocation = PinotServiceManagerAdminApiApplication.class.getClassLoader() .getResource("META-INF/resources/webjars/swagger-ui/2.2.2/"); CLStaticHttpHandler swaggerDist = new CLStaticHttpHandler(new URLClassLoader(new URL[]{swaggerDistLocation})); _httpServer.getServerConfiguration().addHttpHandler(swaggerDist, "/swaggerui-dist/"); }
Example #14
Source File: SOLRAPIClientTest.java From SearchServices with GNU Lesser General Public License v3.0 | 6 votes |
public ClassLoader getResourceClassLoader() { File f = new File("woof", "alfrescoResources"); if (f.canRead() && f.isDirectory()) { URL[] urls = new URL[1]; try { URL url = f.toURI().normalize().toURL(); urls[0] = url; } catch (MalformedURLException e) { throw new AlfrescoRuntimeException("Failed to add resources to classpath ", e); } return URLClassLoader.newInstance(urls, this.getClass().getClassLoader()); } else { return this.getClass().getClassLoader(); } }
Example #15
Source File: BootstrapUtil.java From GriefDefender with MIT License | 6 votes |
public static void addUrlToClassLoader(String name, File input) { try { final ClassLoader classLoader = GDBootstrap.class.getClassLoader(); if (classLoader instanceof URLClassLoader) { try { METHOD_ADD_URL.invoke(classLoader, new URL("jar:file:" + input.getPath() + "!/")); } catch (Throwable t) { t.printStackTrace(); } } else { throw new RuntimeException("Unknown classloader: " + classLoader.getClass()); } } catch (Exception ex) { ex.printStackTrace(); } }
Example #16
Source File: LeakTest.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
private static WeakReference<ClassLoader> testShadow(Class<?> originalTestClass) throws Exception { URLClassLoader originalLoader = (URLClassLoader) originalTestClass.getClassLoader(); URL[] urls = originalLoader.getURLs(); URLClassLoader shadowLoader = new ShadowClassLoader(urls, originalLoader.getParent()); System.out.println("Shadow loader is " + shadowLoader); String className = originalTestClass.getName(); Class<?> testClass = Class.forName(className, false, shadowLoader); if (testClass.getClassLoader() != shadowLoader) { throw new IllegalArgumentException("Loader didn't work: " + testClass.getClassLoader() + " != " + shadowLoader); } Method main = testClass.getMethod("main", String[].class); main.invoke(null, (Object) new String[0]); return new WeakReference<ClassLoader>(shadowLoader); }
Example #17
Source File: TomEEJarScanner.java From tomee with Apache License 2.0 | 6 votes |
@Override public void scan(final JarScanType scanType, final ServletContext context, final JarScannerCallback callback) { super.scan(scanType, context, callback); if (!embeddedSurefireScanning(scanType, context, callback) && isScanClassPath() && !URLClassLoader.class.isInstance(getSystemClassLoader()) && !Boolean.getBoolean("tomee.classpath.scanning.disabled")) { // TODO: check on tomcat upgrade if it is fixed final String cp = System.getProperty("java.class.path"); final Collection<URL> urls = new HashSet<>(); for (final String jar : cp.split(File.pathSeparator)) { if(!jar.isEmpty()){ try { urls.add(new File(jar).toURI().toURL()); } catch (MalformedURLException e) { // no-op } } } doScan(scanType, callback, new LinkedList<>(urls)); } }
Example #18
Source File: ReflectionBenchmarkUniqueAccessTest.java From AVM with MIT License | 6 votes |
private long uniqueInstanceMethodHandleInstanceFieldWriteAccessInvokeExactOnly(int spins) throws Throwable { ReflectionTarget[] targets = new ReflectionTarget[spins]; MethodHandle[] fields = new MethodHandle[spins]; for (int i = 0; i < spins; i++) { ClassLoader loader = new URLClassLoader(new URL[]{ classpathDirectory.toURI().toURL() }); Class<?> clazz = loader.loadClass(targetClassName); targets[i] = (ReflectionTarget) MethodHandles.lookup().findConstructor(clazz, MethodType.methodType(void.class)).invoke(); fields[i] = MethodHandles.lookup().findSetter(clazz, instanceField, Object.class); } Object object = new Object(); long start = System.nanoTime(); for (int i = 0; i < spins; i++) { fields[i].invokeExact(targets[i], object); } long end = System.nanoTime(); return end - start; }
Example #19
Source File: StandaloneTest.java From netbeans with Apache License 2.0 | 6 votes |
@Override protected void setUp() throws Exception { URL api = CommandLine.class.getProtectionDomain().getCodeSource().getLocation(); URL options = Options.class.getProtectionDomain().getCodeSource().getLocation(); loader = new URLClassLoader( new URL[] { api, options }, CommandLine.class.getClassLoader().getParent() ); Thread.currentThread().setContextClassLoader(loader); classCommandLine = loader.loadClass(CommandLine.class.getName()); classOptions = loader.loadClass(Options.class.getName()); methodProcess = classCommandLine.getMethod("process", String[].class); methodUsage = classCommandLine.getMethod("usage", PrintWriter.class); }
Example #20
Source File: LaunchClassChooser.java From osp with GNU General Public License v3.0 | 6 votes |
LaunchableClassMap(String[] names) { jarOrDirectoryNames = names; // create a URL for each jar or directory Collection<URL> urls = new ArrayList<URL>(); // changed by D Brown 2007-11-06 for Linux // changed by F Esquembre and D Brown 2010-03-02 to allow arbitrary base path String basePath = LaunchClassChooser.baseDirectoryPath; if (basePath==null) basePath = OSPRuntime.getLaunchJarDirectory(); for(int i = 0; i<names.length; i++) { String path = XML.getResolvedPath(names[i], basePath); if (!path.endsWith(".jar") && !path.endsWith("/")) { //$NON-NLS-1$ //$NON-NLS-2$ path += "/"; // directories passed to URLClassLoader must end with slash //$NON-NLS-1$ } try { urls.add(new URL("file:"+path)); //$NON-NLS-1$ } catch(MalformedURLException ex) { OSPLog.info(ex+" "+path); //$NON-NLS-1$ } } // create the class loader classLoader = URLClassLoader.newInstance(urls.toArray(new URL[0])); }
Example #21
Source File: ArcTestContainer.java From quarkus with Apache License 2.0 | 6 votes |
@Override public void afterEach(ExtensionContext extensionContext) throws Exception { ClassLoader oldTccl = getRootExtensionStore(extensionContext).get(KEY_OLD_TCCL, ClassLoader.class); Thread.currentThread().setContextClassLoader(oldTccl); URLClassLoader testClassLoader = getRootExtensionStore(extensionContext).get(KEY_TEST_CLASSLOADER, URLClassLoader.class); if (testClassLoader != null) { try { testClassLoader.close(); } catch (IOException e) { e.printStackTrace(); } } shutdown(); }
Example #22
Source File: IndirectlyLoadABundle.java From hottub with GNU General Public License v2.0 | 6 votes |
public boolean testGetAnonymousLogger() throws Throwable { // Test getAnonymousLogger() URLClassLoader loadItUpCL = new URLClassLoader(getURLs(), null); Class<?> loadItUpClazz = Class.forName("LoadItUp1", true, loadItUpCL); ClassLoader actual = loadItUpClazz.getClassLoader(); if (actual != loadItUpCL) { throw new Exception("LoadItUp1 was loaded by an unexpected CL: " + actual); } Object loadItUpAnon = loadItUpClazz.newInstance(); Method testAnonMethod = loadItUpClazz.getMethod("getAnonymousLogger", String.class); try { return (Logger)testAnonMethod.invoke(loadItUpAnon, rbName) != null; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } }
Example #23
Source File: PluginManagerImpl.java From The-5zig-Mod with MIT License | 6 votes |
Class<?> getClassByName(String name, URLClassLoader ignore) { Class<?> clazz = cachedClasses.get(name); if (clazz != null) { return clazz; } for (LoadedPlugin plugin : plugins) { PluginClassLoader classLoader = plugin.getClassLoader(); if (classLoader == ignore) { continue; } try { clazz = classLoader.findClass(name, false); } catch (ClassNotFoundException ignored) { } if (clazz != null) { cachedClasses.put(name, clazz); return clazz; } } return null; }
Example #24
Source File: JdiLoadedByCustomLoader.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String args[]) throws Exception { // create files from given arguments and tools.jar File f1 = new File(args[0]); String home = System.getProperty("java.home"); String tools = ".." + File.separatorChar + "lib" + File.separatorChar + "tools.jar"; File f2 = (new File(home, tools)).getCanonicalFile(); // create class loader URL[] urls = { f1.toURL(), f2.toURL() }; URLClassLoader cl = new URLClassLoader(urls); // load ListConnectors using the class loader // and then invoke the list method. Class c = Class.forName("ListConnectors", true, cl); Method m = c.getDeclaredMethod("list"); Object o = c.newInstance(); m.invoke(o); }
Example #25
Source File: ClassLoad.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { boolean error = true; // Start a dummy server to return 404 HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); HttpHandler handler = new HttpHandler() { public void handle(HttpExchange t) throws IOException { InputStream is = t.getRequestBody(); while (is.read() != -1); t.sendResponseHeaders (404, -1); t.close(); } }; server.createContext("/", handler); server.start(); // Client request try { URL url = new URL("http://localhost:" + server.getAddress().getPort()); String name = args.length >= 2 ? args[1] : "foo.bar.Baz"; ClassLoader loader = new URLClassLoader(new URL[] { url }); System.out.println(url); Class c = loader.loadClass(name); System.out.println("Loaded class \"" + c.getName() + "\"."); } catch (ClassNotFoundException ex) { System.out.println(ex); error = false; } finally { server.stop(0); } if (error) throw new RuntimeException("No ClassNotFoundException generated"); }
Example #26
Source File: ClassLoaderTest.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { File file = new File(BASE); URL[] urls = new URL[1]; urls[0] = file.toURI().toURL(); URLClassLoader ucl = new URLClassLoader(urls); Class<?> c = ucl.loadClass("MyTransform"); Constructor<?> cons = c.getConstructor(new Class[] {}); Object o = cons.newInstance(); // Apache code swallows the ClassNotFoundExc, so we need to // check if the Transform has already been registered by registering // it again and catching an AlgorithmAlreadyRegisteredExc try { Transform.register(MyTransform.URI, "MyTransform"); throw new Exception("ClassLoaderTest failed"); } catch (AlgorithmAlreadyRegisteredException e) { // test passed } }
Example #27
Source File: Configuration.java From claw-compiler with BSD 2-Clause "Simplified" License | 5 votes |
/** * Read all the transformation sets. * * @param sets Parent element "sets" for the transformation set. * @throws Exception If transformation set file does not exist or not well * formatted. */ private void readSets(Element sets) throws Exception { File xsdSchema = Paths.get(_configuration_path, SET_XSD).toFile(); NodeList transformationSets = sets.getElementsByTagName(SET_ELEMENT); for(int i = 0; i < transformationSets.getLength(); ++i) { Element e = (Element) transformationSets.item(i); String setName = e.getAttribute(NAME_ATTR); File setFile = Paths.get(_configuration_path, setName + XML_EXT).toFile(); if(!setFile.exists()) { throw new Exception("Transformation set " + setName + " cannot be found!"); } Document setDocument = parseAndValidate(setFile, xsdSchema); Element root = setDocument.getDocumentElement(); boolean isExternal = root.hasAttribute(JAR_ATTR); // Try to locate the external jar if(isExternal) { String externalJar = root.getAttribute(JAR_ATTR); URLClassLoader loader = loadExternalJar(externalJar); readTransformations(setName, root, loader); } else { readTransformations(setName, root, null); } } }
Example #28
Source File: JaxbMarshallTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
@Test public void marshallClassCastExceptionTest() throws Exception { JAXBContext jaxbContext; Marshaller marshaller; URLClassLoader jaxbContextClassLoader; // Generate java classes by xjc runXjc(XSD_FILENAME); // Compile xjc generated java files compileXjcGeneratedClasses(); // Create JAXB context based on xjc generated package. // Need to create URL class loader ot make compiled classes discoverable // by JAXB context jaxbContextClassLoader = URLClassLoader.newInstance(new URL[] {testWorkDirUrl}); jaxbContext = JAXBContext.newInstance( TEST_PACKAGE, jaxbContextClassLoader); // Create instance of Xjc generated data type. // Java classes were compiled during the test execution hence reflection // is needed here Class classLongListClass = jaxbContextClassLoader.loadClass(TEST_CLASS); Object objectLongListClass = classLongListClass.newInstance(); // Get 'getIn' method object Method getInMethod = classLongListClass.getMethod( GET_LIST_METHOD, (Class [])null ); // Invoke 'getIn' method List<Long> inList = (List<Long>)getInMethod.invoke(objectLongListClass); // Add values into the jaxb object list inList.add(Long.valueOf(0)); inList.add(Long.valueOf(43)); inList.add(Long.valueOf(1000000123)); // Marshall constructed complex type variable to standard output. // In case of failure the ClassCastException will be thrown marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(objectLongListClass, System.out); }
Example #29
Source File: GenericGeneratorsTest.java From coroutines with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void mustCreateAndRunIfObjectStatements() throws Exception { // Augment signature methodNode.desc = Type.getMethodDescriptor( Type.getType(String.class), new Type[] { Type.getType(Object.class), Type.getType(Object.class) }); // Initialize variable table VariableTable varTable = new VariableTable(classNode, methodNode); Variable intVar1 = varTable.getArgument(1); Variable intVar2 = varTable.getArgument(2); // Update method logic /** * if (arg1 == arg2) { * return "match"; * } * return "nomatch"; */ methodNode.instructions = merge( ifObjectsEqual( loadVar(intVar1), loadVar(intVar2), returnValue(Type.getType(String.class), loadStringConst("match"))), returnValue(Type.getType(String.class), loadStringConst("nomatch")) ); Object testObj1 = "test1"; Object testObj2 = "test2"; // Write to JAR file + load up in classloader -- then execute tests try (URLClassLoader cl = createJarAndLoad(classNode)) { Object obj = cl.loadClass(STUB_CLASSNAME).newInstance(); assertEquals("match", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, testObj1, testObj1)); assertEquals("nomatch", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, testObj1, testObj2)); assertEquals("match", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, testObj2, testObj2)); } }
Example #30
Source File: DependencyMediator.java From dependency-mediator with Apache License 2.0 | 5 votes |
private static Collection<URLClassLoader> getClassLoaders(ClassLoader baseClassLoader) { Collection<URLClassLoader> loaders = new ArrayList<URLClassLoader>(); ClassLoader loader = baseClassLoader; while (loader != null) { //Ignore if ("sun.misc.Launcher$ExtClassLoader".equals(loader.getClass().getName())) { break; } if (loader instanceof URLClassLoader) { loaders.add((URLClassLoader) loader); } loader = loader.getParent(); } return loaders; }