当前位置: 首页>>代码示例>>Java>>正文


Java URLClassLoader类代码示例

本文整理汇总了Java中java.net.URLClassLoader的典型用法代码示例。如果您正苦于以下问题:Java URLClassLoader类的具体用法?Java URLClassLoader怎么用?Java URLClassLoader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


URLClassLoader类属于java.net包,在下文中一共展示了URLClassLoader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: checkCommands

import java.net.URLClassLoader; //导入依赖的package包/类
private void checkCommands(final String os, final String... command) throws ReflectiveOperationException {
	final URL[] urLs = ((URLClassLoader) Main.class.getClassLoader()).getURLs();
	ThreadClassLoaderScope scope = null;
	try {
		System.setProperty("os.name", os);
		final URLClassLoader urlClassLoader = new URLClassLoader(urLs, null);
		scope = new ThreadClassLoaderScope(urlClassLoader);
		final Object terra = urlClassLoader.loadClass("org.ligoj.app.plugin.prov.terraform.TerraformUtils").newInstance();
		final Object mock = MethodUtils.invokeStaticMethod(urlClassLoader.loadClass("org.mockito.Mockito"), "mock",
				urlClassLoader.loadClass("org.ligoj.bootstrap.resource.system.configuration.ConfigurationResource"));
		FieldUtils.writeField(terra, "configuration", mock, true);
		Assert.assertEquals(Arrays.asList(command),
				((ProcessBuilder) MethodUtils.invokeMethod(terra, true, "newBuilder", new Object[] { new String[] { "terraform" } }))
						.command());
	} finally {
		IOUtils.closeQuietly(scope);
	}
}
 
开发者ID:ligoj,项目名称:plugin-prov,代码行数:19,代码来源:TerraformUtilsTest.java

示例2: getLibraryResolver

import java.net.URLClassLoader; //导入依赖的package包/类
@Override
public LibraryResolver getLibraryResolver(Object realm) {
    if (!(realm instanceof Plugin))
        throw new IllegalArgumentException("Only realms of type " + Plugin.class.getName() + " are supported");
    Plugin plugin = (Plugin) realm;
    String name = plugin.getDescription().getName();
    ClassLoader classLoader = realm.getClass().getClassLoader();
    if (!(classLoader instanceof URLClassLoader))
        throw new UnsupportedOperationException("Plugin " + name + " was not loaded by a URLClassLoader");
    return libraryResolvers.computeIfAbsent(name, n -> new ClassLoaderLibraryResolver(
            repositorySystem,
            createSession(),
            remoteRepositorySupplier,
            (URLClassLoader) classLoader,
            plugin.getLogger()
    ));
}
 
开发者ID:MCCityVille,项目名称:libmanager,代码行数:18,代码来源:BungeeCordLibraryManager.java

示例3: getJRTFS

import java.net.URLClassLoader; //导入依赖的package包/类
@CheckForNull
public static Path getJRTFS() throws IOException {
    final File java9 = getJava9Home();
    if (java9 == null) {
        return null;
    }
    final File jrtFsProvider = new File(java9,"jrt-fs.jar"); //NOI18N
    if (jrtFsProvider.exists() && jrtFsProvider.isFile() && jrtFsProvider.canRead()) {
        final ClassLoader cl = new URLClassLoader(new URL[]{
            BaseUtilities.toURI(jrtFsProvider).toURL()
        });
        final ServiceLoader<FileSystemProvider> sl = ServiceLoader.load(FileSystemProvider.class, cl);
        FileSystemProvider jrtp = null;
        for (FileSystemProvider fsp : sl) {
            if ("jrt".equals(fsp.getScheme())) {    //NOI18N
                jrtp = fsp;
                break;
            }
        }
        if (jrtp != null) {
            return jrtp.getPath(URI.create("jrt:/"));   //NOI18N
        }
    }
    return null;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:26,代码来源:TestUtilities.java

示例4: run

import java.net.URLClassLoader; //导入依赖的package包/类
@Override
public void run() {


    try {
        URL u = this.getClass().getClassLoader().getResource("DummyClass.class");
        String path = u.getPath();
        String parent = u.getPath().substring(0, path.lastIndexOf('/')+1);
        URL parentURL = new URL(u, parent);
        System.out.println(parentURL);
        /* Load lots of class by creating multiple classloaders */
        for(;;) {
            ClassLoader cl = new URLClassLoader(new URL[] {parentURL}, null);
            cl.loadClass("DummyClass");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:20,代码来源:TestDaemonThread.java

示例5: testJarAtPath

import java.net.URLClassLoader; //导入依赖的package包/类
/**
 * Given a path with a jar, make a classloader with that jar on the
 * classpath, and check that findContainingJar can correctly
 * identify the path of the jar.
 */
private void testJarAtPath(String path) throws Exception {
  File jar = new File(path).getAbsoluteFile();
  assertTrue(jar.exists());

  URL urls[] = new URL[] {
    jar.toURI().toURL()
  };

  ClassLoader cl = new URLClassLoader(urls);
  Class clazz = Class.forName(CLASSNAME, true, cl);
  assertNotNull(clazz);

  String containingJar = ClassUtil.findContainingJar(clazz);
  assertEquals(jar.getAbsolutePath(), containingJar);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:21,代码来源:TestMRCJCJobConf.java

示例6: setUp

import java.net.URLClassLoader; //导入依赖的package包/类
/** This method is called before the actual test method to allow
     * the benchmark to prepare accordingly to informations available
     * through {@link #getIterationCount}, {@link #getArgument} and {@link #getName}.
     * This method can use assertions to signal failure of the test.
     * @throws Exception This method can throw any exception which is treated as a error in the testing code
     * or testing enviroment.
     */
    protected void setUp() throws Exception {
        int size = getIntValue(CLASS_NO_KEY);
        
        FileObject[] fileObjects = mfstest.setUpFileObjects(size);
        FileWrapper[] wrappers = mfstest.getFileWrappers();
        
        URLClassLoader[] parents = new URLClassLoader[wrappers.length];
        for (int i = 0; i < parents.length; i++) {
            parents[i] = new URLClassLoader(new URL[] { wrappers[i].getMnt().toURL() });
        }
        
//        MultiURLClassLoader multicloader = new MultiURLClassLoader(new URL[] {}, parents);
        ClassLoader multicloader = new ProxyClassLoader(parents);
        
        instanceObjects = fileObjects2InstanceDataObjects(fileObjects);
        setClassLoader(instanceObjects, multicloader);
    }
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:25,代码来源:MultiURLClassLoaderTest.java

示例7: JdkCompiler

import java.net.URLClassLoader; //导入依赖的package包/类
public JdkCompiler(){
    options = new ArrayList<String>();
    options.add("-target");
    options.add("1.6");
    StandardJavaFileManager manager = compiler.getStandardFileManager(diagnosticCollector, null, null);
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader instanceof URLClassLoader 
            && (! loader.getClass().getName().equals("sun.misc.Launcher$AppClassLoader"))) {
        try {
            URLClassLoader urlClassLoader = (URLClassLoader) loader;
            List<File> files = new ArrayList<File>();
            for (URL url : urlClassLoader.getURLs()) {
                files.add(new File(url.getFile()));
            }
            manager.setLocation(StandardLocation.CLASS_PATH, files);
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
    classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoaderImpl>() {
        public ClassLoaderImpl run() {
            return new ClassLoaderImpl(loader);
        }
    });
    javaFileManager = new JavaFileManagerImpl(manager, classLoader);
}
 
开发者ID:zhuxiaolei,项目名称:dubbo2,代码行数:27,代码来源:JdkCompiler.java

示例8: test_should_load_testng_version

import java.net.URLClassLoader; //导入依赖的package包/类
@Test
public void test_should_load_testng_version() throws MalformedURLException {
    // given
    File junitFile = Maven
        .resolver()
        .resolve("org.testng:testng:" + testNgVersion)
        .withoutTransitivity()
        .asSingleFile();

    URL[] junitUrl = {junitFile.toURI().toURL()};
    URLClassLoader urlClassLoader = new URLClassLoader(junitUrl);

    // when
    String junitVersion =
        LoaderVersionExtractor.getVersionFromClassLoader(LoaderVersionExtractor.LIBRARY_TEST_NG, urlClassLoader);

    // then
    assertThat(junitVersion).isEqualTo(testNgVersion);
}
 
开发者ID:arquillian,项目名称:smart-testing,代码行数:20,代码来源:LoaderVersionExtractorTestNgTest.java

示例9: classLoader

import java.net.URLClassLoader; //导入依赖的package包/类
public static ClassLoader classLoader(ClassLoader parent,
		List<File> locations) {
	URL[] urls = new URL[locations.size()];
	for (int i = 0; i < locations.size(); i++) {
		File location = locations.get(i);
		URL asUrl = fileToUrl(location);
		// TODO own type so we don't need to slash back and forth
		asUrl = withTrailingSlashIfDir(asUrl);
		urls[i] = asUrl;
	}
	if (parent != null) {
		return new URLClassLoader(urls, parent);
	} else {
		return new URLClassLoader(urls);
	}
}
 
开发者ID:wipu,项目名称:iwant-demo,代码行数:17,代码来源:Iwant.java

示例10: testShadow

import java.net.URLClassLoader; //导入依赖的package包/类
private static WeakReference<ClassLoader>
        testShadow(Class<?> originalTestClass) throws Exception {
    String[] cpaths = System.getProperty("test.classes", ".")
                            .split(File.pathSeparator);
    URL[] urls = new URL[cpaths.length];
    for (int i=0; i < cpaths.length; i++) {
        urls[i] = Paths.get(cpaths[i]).toUri().toURL();
    }

    URLClassLoader shadowLoader =
            new ShadowClassLoader(urls, originalTestClass.getClassLoader().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);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:23,代码来源:LeakTest.java

示例11: toFile

import java.net.URLClassLoader; //导入依赖的package包/类
@Test
public void toFile() throws IOException {
	ThreadClassLoaderScope scope = null;
	try {
		final PluginsClassLoader classLoader = Mockito.mock(PluginsClassLoader.class);
		scope = new ThreadClassLoaderScope(new URLClassLoader(new URL[0], classLoader));
		final File file = new File("");
		final Subscription entity = new Subscription();
		entity.setId(15);
		Mockito.when(classLoader.toFile(entity, "15", "some")).thenReturn(file);
		Assert.assertSame(file, resource.toFile(entity, "some"));
		Assert.assertNotNull(PluginsClassLoader.getInstance());
	} finally {
		IOUtils.closeQuietly(scope);
	}
}
 
开发者ID:ligoj,项目名称:plugin-prov,代码行数:17,代码来源:TerraformResourceTest.java

示例12: addURLs

import java.net.URLClassLoader; //导入依赖的package包/类
private static void addURLs(URL[] jars) throws Exception {
    URLClassLoader loader =
        (URLClassLoader)Thread.currentThread().getContextClassLoader();

    //bypass protected access.
    Method addURL =
        URLClassLoader.class.getDeclaredMethod("addURL",
                                               new Class[] {
                                                   URL.class
                                               });

    addURL.setAccessible(true); //pound sand.

    for (int i=0; i<jars.length; i++) {
        addURL.invoke(loader, new Object[] { jars[i] });
    }
}
 
开发者ID:EnFlexIT,项目名称:AgentWorkbench,代码行数:18,代码来源:Runner.java

示例13: main

import java.net.URLClassLoader; //导入依赖的package包/类
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()));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:27,代码来源:B7050028.java

示例14: getDriverLoaderByName

import java.net.URLClassLoader; //导入依赖的package包/类
/**
 * 加载对应路径jar包里的对应驱动
 *
 * @param fname 对应路径  如: lib4/ojdbc14.jar
 * @param dname 驱动名  如: oracle.jdbc.driver.OracleDriver
 * @return 加载到的驱动    java.sql.Driver
 * @throws Exception
 * @author tangxr
 */
public static Driver getDriverLoaderByName(String fname, String dname) throws Exception {
    if (null == fname || "".equals(fname)) {
        LOG.error("对应的驱动路径不存在,请确认.");
        return null;
    }
    if (null == dname || "".equals(dname)) {
        LOG.error("对应的驱动类的名字不存在.");
        return null;
    }
    File file = new File(fname);
    if (!file.exists()) {
        LOG.error("对应的驱动jar不存在.");
        return null;
    }
    URLClassLoader loader = new URLClassLoader(new URL[]{file.toURI().toURL()});
    loader.clearAssertionStatus();

    return (Driver) loader.loadClass(dname).newInstance();

}
 
开发者ID:DevOpsStudio,项目名称:Re-Collector,代码行数:30,代码来源:DriverLoader.java

示例15: testCompilation

import java.net.URLClassLoader; //导入依赖的package包/类
@Test
@Ignore("Causes problems with gradle test invocation")
public void testCompilation() throws ClassNotFoundException, IllegalAccessException, InstantiationException
{
  List<IDirectory> sourcePath = new ArrayList<>( ManifoldHost.getGlobalModule().getSourcePath() );
  sourcePath.add( ManifoldHost.getFileSystem().getIDirectory( JavacTask.class.getProtectionDomain().getCodeSource().getLocation() ) );
  ClassLoader cl = new URLClassLoader( sourcePath.stream().map( e ->
                                                                {
                                                                  try
                                                                  {
                                                                    return e.toURI().toURL();
                                                                  }
                                                                  catch( MalformedURLException e1 )
                                                                  {
                                                                    throw new RuntimeException( e1 );
                                                                  }
                                                                } ).toArray( URL[]::new ), null );
  Class<?> cls = Class.forName( Tests.class.getName(), true, cl );
  cls.newInstance();
}
 
开发者ID:manifold-systems,项目名称:manifold,代码行数:21,代码来源:CompilationTest.java


注:本文中的java.net.URLClassLoader类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。