本文整理汇总了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);
}
}
示例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()
));
}
示例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;
}
示例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();
}
}
示例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);
}
示例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);
}
示例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);
}
示例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);
}
示例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);
}
}
示例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);
}
示例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);
}
}
示例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] });
}
}
示例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()));
}
示例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();
}
示例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();
}