Java 类java.net.URLClassLoader 实例源码
项目:plugin-prov
文件:TerraformUtilsTest.java
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);
}
}
项目:libmanager
文件:BungeeCordLibraryManager.java
@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()
));
}
项目:incubator-netbeans
文件:TestUtilities.java
@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;
}
项目:jdk8u-jdk
文件:TestDaemonThread.java
@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();
}
}
项目:hadoop
文件:TestMRCJCJobConf.java
/**
* 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);
}
项目:incubator-netbeans
文件:MultiURLClassLoaderTest.java
/** 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);
}
项目:dubbo2
文件:JdkCompiler.java
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);
}
项目:smart-testing
文件:LoaderVersionExtractorTestNgTest.java
@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);
}
项目:iwant-demo
文件:Iwant.java
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);
}
}
项目:openjdk-jdk10
文件:LeakTest.java
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);
}
项目:plugin-prov
文件:TerraformResourceTest.java
@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);
}
}
项目:AgentWorkbench
文件:Runner.java
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] });
}
}
项目:openjdk-jdk10
文件:B7050028.java
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()));
}
项目:Re-Collector
文件:DriverLoader.java
/**
* 加载对应路径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();
}
项目:manifold
文件:CompilationTest.java
@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();
}
项目:ipack
文件:MissingEntryException.java
public String getDebugMsg()
{
if (debugMsg == null)
{
debugMsg = "Can not find entry " + key + " in resource file " + resource + " for the locale " + locale + ".";
if (loader instanceof URLClassLoader)
{
URL[] urls = ((URLClassLoader) loader).getURLs();
debugMsg += " The following entries in the classpath were searched: ";
for (int i = 0; i != urls.length; i++)
{
debugMsg += urls[i] + " ";
}
}
}
return debugMsg;
}
项目:jdk8u-jdk
文件:JdiLoadedByCustomLoader.java
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);
}
项目:lams
文件:ClasspathUtilsTest.java
public void testGetClasspathComponentsFromClassLoader() throws MalformedURLException
{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try
{
File file = new File("/some/package/dir");
URL[] urls = new URL[] { file.toURL() };
// assert my package can't be found yet
List components = ClasspathUtils.getClasspathComponents();
Collections.sort(components);
assertTrue(Collections.binarySearch(components, file.getPath()) < 0);
// test my package is found
URLClassLoader ucl = new URLClassLoader(urls, classLoader);
Thread.currentThread().setContextClassLoader(ucl);
components = ClasspathUtils.getClasspathComponents();
Collections.sort(components);
assertTrue( Collections.binarySearch(components, file.getAbsolutePath()) >= 0);
}
finally
{
Thread.currentThread().setContextClassLoader(classLoader);
}
}
项目:elasticsearch_my
文件:TikaImpl.java
static PermissionCollection getRestrictedPermissions() {
Permissions perms = new Permissions();
// property/env access needed for parsing
perms.add(new PropertyPermission("*", "read"));
perms.add(new RuntimePermission("getenv.TIKA_CONFIG"));
// add permissions for resource access:
// classpath
addReadPermissions(perms, JarHell.parseClassPath());
// plugin jars
if (TikaImpl.class.getClassLoader() instanceof URLClassLoader) {
addReadPermissions(perms, ((URLClassLoader)TikaImpl.class.getClassLoader()).getURLs());
}
// jvm's java.io.tmpdir (needs read/write)
perms.add(new FilePermission(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "-",
"read,readlink,write,delete"));
// current hacks needed for POI/PDFbox issues:
perms.add(new SecurityPermission("putProviderProperty.BC"));
perms.add(new SecurityPermission("insertProvider"));
perms.add(new ReflectPermission("suppressAccessChecks"));
// xmlbeans, use by POI, needs to get the context classloader
perms.add(new RuntimePermission("getClassLoader"));
perms.setReadOnly();
return perms;
}
项目:uavstack
文件:PackageHelper.java
private static void getClassNameFromClsLoader(List<String> fileNames, boolean childPackage, String packagePath,
URL url, ClassLoader cl) {
List<String> tempFileNames = null;
if (url != null) {
String type = url.getProtocol();
if ("file".equals(type)) {
tempFileNames = getClassNameByFile(url.getPath(), childPackage);
}
else if ("jar".equals(type)) {
tempFileNames = getClassNameByJar(url.getPath(), childPackage);
}
}
else {
tempFileNames = getClassNameByJars(((URLClassLoader) cl).getURLs(), packagePath, childPackage);
}
if (tempFileNames != null) {
fileNames.addAll(tempFileNames);
}
}
项目:openjdk-jdk10
文件:VersionHelper.java
/**
* @param className A non-null fully qualified class name.
* @param codebase A non-null, space-separated list of URL strings.
*/
public Class<?> loadClass(String className, String codebase)
throws ClassNotFoundException, MalformedURLException {
ClassLoader parent = getContextClassLoader();
ClassLoader cl =
URLClassLoader.newInstance(getUrlArray(codebase), parent);
return loadClass(className, cl);
}
项目:openjdk-jdk10
文件:ClassLoader_loadClass01.java
public static String test(int i) throws ClassNotFoundException {
final URLClassLoader classLoader = new URLClassLoader(new URL[0], String.class.getClassLoader());
if (i == 0) {
return classLoader.loadClass("java.lang.String").toString();
} else if (i == 1) {
return classLoader.loadClass("[Ljava.lang.String;").toString();
} else if (i == 2) {
return classLoader.loadClass("java.lang.String[]").toString();
}
return null;
}
项目:gradle-circle-style
文件:CircleStylePluginTests.java
private static String pluginClasspath() {
URLClassLoader classloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
List<String> classpath = new ArrayList<>();
for (URL url : classloader.getURLs()) {
classpath.add(url.getFile());
}
return Joiner.on(':').join(classpath);
}
项目:util4j
文件:BufferBuilderDemo.java
/**
* 获取源码目录下指定包下的类
* @param root
* @param pkg
* @return
* @throws Exception
*/
public List<Class<?>> getClassInfo(String root,String pkg) throws Exception
{
List<Class<?>> list=new ArrayList<Class<?>>();
String suffix=".java";
File rootDir=new File(root);
Set<File> files=FileUtil.findFileByDirAndSub(rootDir,suffix);
URLClassLoader loader=new URLClassLoader(new URL[]{rootDir.toURI().toURL()});
try {
// 获取路径长度
int clazzPathLen = rootDir.getAbsolutePath().length() + 1;
for(File file:files)
{
String className = file.getAbsolutePath();
className = className.substring(clazzPathLen, className.length() - suffix.length());
className = className.replace(File.separatorChar, '.');
try {
Class<?> clazz=loader.loadClass(className);
String pkgName=clazz.getPackage().getName();
if(pkgName.equals(pkg))
{
list.add(clazz);
}
} catch (Exception e) {
}
}
} finally {
loader.close();
}
return list;
}
项目:guava-mock
文件:ClassPathTest.java
@AndroidIncompatible // Android forbids null parent ClassLoader
// https://github.com/google/guava/issues/2152
public void testClassPathEntries_URLClassLoader_pathWithSpace() throws Exception {
URL url = new URL("file:///c:/Documents and Settings/");
URLClassLoader classloader = new URLClassLoader(new URL[] {url}, null);
assertThat(ClassPath.Scanner.getClassPathEntries(classloader))
.containsExactly(new File("/c:/Documents and Settings/"), classloader);
}
项目:gradle-clojure
文件:ClojureWorker.java
public static ClojureRuntime get() {
String[] classpathElements = System.getProperty("shim.classpath").split(File.pathSeparator);
URL[] classpathUrls = Arrays.stream(classpathElements)
.map(Paths::get)
.map(Path::toUri)
.map(safe(URI::toURL))
.toArray(size -> new URL[size]);
URLClassLoader loader = new ClojureWorkerClassLoader(classpathUrls, ClojureWorker.class.getClassLoader());
ClojureRuntimeShim shim = ClojureRuntimeShim.newRuntime(loader, "gradle-clojure");
return new ClojureRuntime(loader, shim);
}
项目:Hydrazine
文件:ModuleManager.java
/**
* Returns a module extracted from a jar file.
* @param path the filename of the module
* @return a module
* @throws Exception if something goes wrong, an exception is thrown
*/
public Module getModuleFromJar(String path) throws Exception
{
Module m = null;
JarFile modFile = new JarFile(path);
Manifest mf = modFile.getManifest();
Attributes attr = mf.getMainAttributes();
String mainClass = attr.getValue(Attributes.Name.MAIN_CLASS);
URLClassLoader classLoader = new URLClassLoader(new URL[]{ new File(path).toURI().toURL() });
Class c = classLoader.loadClass(mainClass);
Class[] interfaces = c.getInterfaces();
classLoader.close();
boolean isPlugin = false;
for(int i = 0; i < interfaces.length && !isPlugin; i++)
{
if(interfaces[i].getName().equals("com.github.hydrazine.module.Module"))
{
isPlugin = true;
}
}
if(isPlugin)
{
m = (Module) c.newInstance();
}
else
{
System.out.println(Hydrazine.warnPrefix + "\"" + path + "\" isn't a valid module. You should remove it from the directory.");
}
modFile.close();
return m;
}
项目:android-perftracking
文件:ClassProvider.java
public ClassProvider(String classpath) {
try {
ArrayList<URL> urls = new ArrayList<URL>();
for (String path : classpath.split(File.pathSeparator)) {
urls.add(Paths.get(path).toFile().toURI().toURL());
}
_classLoader = new URLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader());
} catch (Exception e) {
throw new RuntimeException("Failed to create class loader");
}
}
项目:kestrel
文件:KestrelRunnerBase.java
/**
* Add a library URL.
*
* @param url URL to add. If this URL is already in the list, it is not added.
*
* @throws NullPointerException If <code>url</code> is <code>null</code>.
*/
public void addLibraryURL(URL url)
throws NullPointerException {
if (url == null)
throw new NullPointerException("Cannot add library URL: null");
if (libraryUrlList.contains(url))
return;
libraryUrlList.add(url);
loader = new URLClassLoader(libraryUrlList.toArray(new URL[0]));
return;
}
项目:guava-mock
文件:FinalizableReferenceQueue.java
/** Creates a class loader with the given base URL as its classpath. */
URLClassLoader newLoader(URL base) {
// We use the bootstrap class loader as the parent because Finalizer by design uses
// only standard Java classes. That also means that FinalizableReferenceQueueTest
// doesn't pick up the wrong version of the Finalizer class.
return new URLClassLoader(new URL[] {base}, null);
}
项目:FridaAndroidTracer
文件:FridaAndroidTracer.java
private static ClassLoader loadJars(String[] jarFiles) {
URL[] urls = Stream.of(jarFiles)
.map(name -> {
try {
return new File(name).toURI().toURL();
} catch (MalformedURLException e) {
System.out.println("Fail to load jar file: " + name);
e.printStackTrace();
return null;
}
})
.toArray(URL[]::new);
return URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());
}
项目:EvoMaster
文件:ClassScanner.java
private static void searchInCurrentClassLoaderIfUrlOne(List<String> prefixes, Set<ClassName> names) {
ClassLoader loader = ClassScanner.class.getClassLoader();
while (loader != null) {
if (loader instanceof URLClassLoader) {
URLClassLoader urlLoader = (URLClassLoader) loader;
for (URL url : urlLoader.getURLs()) {
try {
URI uri = url.toURI();
File file = new File(uri);
String path = file.getAbsolutePath();
if(file.isDirectory()){
scanDirectory(prefixes, names, file, path);
} else if(path.endsWith(".jar")){
scanJar(prefixes, names, path);
}
} catch (Exception e) {
SimpleLogger.error("Error while parsing URL " + url);
continue;
}
}
}
loader = loader.getParent();
}
}
项目:MaxSim
文件:ClassUnloadCommon.java
public static ClassLoader newClassLoader() {
try {
return new URLClassLoader(new URL[] {
Paths.get(System.getProperty("test.classes",".") + File.separatorChar + "classes").toUri().toURL(),
}, null);
} catch (MalformedURLException e){
throw new RuntimeException("Unexpected URL conversion failure", e);
}
}
项目:angel
文件:ConfUtils.java
private static void loadJar(String jarFile) throws IOException {
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<? extends URLClassLoader> sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(sysloader, new File(jarFile).toURI().toURL());
} catch (Throwable t) {
throw new IOException("Error, could not add URL to system classloader", t);
}
}
项目:imagingbook-common
文件:FileUtils.java
/**
* Lists (to System.out) the paths where classes are loaded from.
*/
public static void printClassPath() {
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader) cl).getURLs();
for (URL url : urls) {
System.out.println(url.getPath());
}
}
项目:OpenJSharp
文件:Options.java
/**
* Finds the <tt>META-INF/sun-jaxb.episode</tt> file to add as a binding customization.
*/
public void scanEpisodeFile(File jar) throws BadCommandLineException {
try {
URLClassLoader ucl = new URLClassLoader(new URL[]{jar.toURL()});
Enumeration<URL> resources = ucl.findResources("META-INF/sun-jaxb.episode");
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
addBindFile(new InputSource(url.toExternalForm()));
}
} catch (IOException e) {
throw new BadCommandLineException(
Messages.format(Messages.FAILED_TO_LOAD,jar,e.getMessage()), e);
}
}
项目:Java-9-Programming-By-Example
文件:ClassLister.java
private void listClasses(URLClassLoader loader) {
URL[] urls = loader.getURLs();
for (final URL url : urls) {
log.info("Listing classes for URL {}", url);
listClasses(loader, url);
}
}
项目:GitHub
文件:ProxyProcessor.java
private static Processor createClassLoaderDelegate() {
try {
if (cachedProxyClassLoader == null) {
cachedProxyClassLoader = new ProxyClassLoader(
((URLClassLoader) ProxyProcessor.class.getClassLoader()).getURLs(),
Thread.currentThread().getContextClassLoader());
}
return (Processor) cachedProxyClassLoader.loadClass(DELEGATE_CLASS).newInstance();
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
项目:minsx-java-example
文件:Main.java
@Test
public void test() throws Exception {
URL url = new URL("file:E:/JavaJars/OtherJar/runner.jar");
URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader());
Class<?> clazz = urlClassLoader.loadClass("com.example.Runner");
//Runnable runnable = (Runnable) clazz.newInstance();
//runnable.run();
Method method = clazz.getMethod("run");
method.invoke(clazz.newInstance());
urlClassLoader.close();
}
项目:openjdk-jdk10
文件:TestHumongousNonArrayAllocation.java
public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
IllegalAccessException, IOException {
if (args.length != 1) {
throw new Error("Test Bug: Expected class name wasn't provided as command line argument");
}
G1SampleClass sampleClass = G1SampleClass.valueOf(args[0]);
Path wrkDir = Files.createTempDirectory(Paths.get(""), CLASS_NAME_PREFIX);
URL[] url = {wrkDir.toUri().toURL()};
URLClassLoader urlLoader = new URLClassLoader(url);
Object sampleObject;
try {
sampleObject = sampleClass.getCls(urlLoader, wrkDir, CLASS_NAME_PREFIX).newInstance();
} catch (Throwable throwable) {
throw new AssertionError("Test Bug: Cannot create object of provided class", throwable);
}
boolean isHumongous = WB.g1IsHumongous(sampleObject);
boolean shouldBeHumongous = (sampleClass.expectedInstanceSize() > (WB.g1RegionSize() / 2));
// Sanity check
Asserts.assertEquals(WB.getObjectSize(sampleObject), sampleClass.expectedInstanceSize(),
String.format("Test Bug: Object of class %s is expected to take %d bytes but it takes %d.",
sampleClass.name(), sampleClass.expectedInstanceSize(), WB.getObjectSize(sampleObject)));
// Test check
Asserts.assertEquals(isHumongous, shouldBeHumongous,
String.format("Object of class %s is expected to be %shumongous but it is not",
sampleClass.name(), (shouldBeHumongous ? "" : "non-")));
}