本文整理汇总了Java中java.net.URLClassLoader.loadClass方法的典型用法代码示例。如果您正苦于以下问题:Java URLClassLoader.loadClass方法的具体用法?Java URLClassLoader.loadClass怎么用?Java URLClassLoader.loadClass使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.URLClassLoader
的用法示例。
在下文中一共展示了URLClassLoader.loadClass方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: go
import java.net.URLClassLoader; //导入方法依赖的package包/类
void go(String[] args) throws IOException, URISyntaxException, ClassNotFoundException,
NoSuchMethodException, InvocationTargetException, IllegalAccessException {
if (!handleVersion(args)) return;
if (!handleMonkeyParse(args[0])) return;
if (!handleDownload()) return;
URL urls[] = new URL[localJars.size()];
for (int i = 0; i < urls.length; ++i) {
urls[i] = localJars.get(i).toURI().toURL();
}
URLClassLoader classLoader = new URLClassLoader(urls);
Class clazz = classLoader.loadClass(entryPoint);
Method method = clazz.getMethod("main", String[].class);
String newArgs[] = new String[args.length - 1];
for (int i = 0; i < newArgs.length; ++i) {
newArgs[i] = args[i + 1];
}
try {
method.invoke(null, (Object) newArgs);
} catch(NoClassDefFoundError e) {
out.printf(String.format("Possible bootstrap problem. Try deleting %s",
getDownloadsFolder()));
}
}
示例2: klassLoader
import java.net.URLClassLoader; //导入方法依赖的package包/类
static boolean klassLoader(URL baseURL,
String resource,
boolean expectToFind,
boolean expectbDotJar,
boolean expectcDotJar) throws IOException {
debug("----------------------------------");
debug("Running test looking for " + resource);
URLClassLoader loader = getLoader(baseURL);
httpServer.reset();
Class<?> ADotAKlass = null;
try {
ADotAKlass = loader.loadClass("a.A");
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
throw new RuntimeException("Error in test: " + cnfe);
}
URL u = ADotAKlass.getResource(resource);
if (expectToFind && u == null) {
System.out.println("Expected to find " + resource + " but didn't");
return false;
}
debug("HttpServer: " + httpServer);
if (!expectbDotJar && httpServer.bDotJar > 0) {
debug("Unexpeced request sent to the httpserver for b.jar");
return false;
}
if (!expectcDotJar && httpServer.cDotJar > 0) {
debug("Unexpeced request sent to the httpserver for c.jar");
return false;
}
return true;
}
示例3: main
import java.net.URLClassLoader; //导入方法依赖的package包/类
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
}
}
示例4: start
import java.net.URLClassLoader; //导入方法依赖的package包/类
public void start(String[] args, File gradleHome) throws Exception {
File gradleJar = findLauncherJar(gradleHome);
URLClassLoader contextClassLoader = new URLClassLoader(new URL[]{gradleJar.toURI().toURL()}, ClassLoader.getSystemClassLoader().getParent());
Thread.currentThread().setContextClassLoader(contextClassLoader);
Class<?> mainClass = contextClassLoader.loadClass("org.gradle.launcher.GradleMain");
Method mainMethod = mainClass.getMethod("main", String[].class);
mainMethod.invoke(null, new Object[]{args});
if (contextClassLoader instanceof Closeable) {
((Closeable) contextClassLoader).close();
}
}
示例5: executeJdbcAllQuery
import java.net.URLClassLoader; //导入方法依赖的package包/类
@Test
public void executeJdbcAllQuery() throws Exception {
// print class path for debugging
System.out.println("java.class.path:");
System.out.println(System.getProperty("java.class.path"));
final URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(loader, getJdbcUrl());
Class<?> clazz = loader.loadClass("org.apache.drill.jdbc.Driver");
try {
Driver driver = (Driver) clazz.newInstance();
try (Connection c = driver.connect("jdbc:drill:drillbit=localhost:31010", null);
Statement s = c.createStatement();
ResultSet result = s.executeQuery("select * from (VALUES 1)");) {
while (result.next()) {
System.out.println(result.getObject(1));
}
}
} catch (Exception ex) {
throw ex;
}
}
示例6: deserializeWithDependencies
import java.net.URLClassLoader; //导入方法依赖的package包/类
static Object deserializeWithDependencies ( byte[] serialized, final String[] dependencies, final Class<?>[] classDependencies, final Class<?> customDeserializer )
throws Exception {
File[] jars = dependencies.length > 0 ? Maven.resolver().resolve(dependencies).withoutTransitivity().asFile() : new File[0];
URL[] urls = new URL[jars.length];
for ( int i = 0; i < jars.length; i++ ) {
urls[ i ] = jars[ i ].toURI().toURL();
}
URLClassLoader isolatedClassLoader = new URLClassLoader(urls, null) {
{
for ( Class<?> clazz : classDependencies ) {
byte[] classAsBytes = ClassFiles.classAsBytes(clazz);
defineClass(clazz.getName(), classAsBytes, 0, classAsBytes.length);
}
byte[] deserializerClassBytes = ClassFiles.classAsBytes(Deserializer.class);
defineClass(Deserializer.class.getName(), deserializerClassBytes, 0, deserializerClassBytes.length);
if ( customDeserializer != null ) {
try {
Method method = customDeserializer.getMethod("getExtraDependencies");
for ( Class extra : (Class[])method.invoke(null)) {
deserializerClassBytes = ClassFiles.classAsBytes(extra);
defineClass(extra.getName(), deserializerClassBytes, 0, deserializerClassBytes.length);
}
} catch ( NoSuchMethodException e ) { }
deserializerClassBytes = ClassFiles.classAsBytes(customDeserializer);
defineClass(customDeserializer.getName(), deserializerClassBytes, 0, deserializerClassBytes.length);
}
}
};
Class<?> deserializerClass = isolatedClassLoader.loadClass(customDeserializer != null ? customDeserializer.getName() : Deserializer.class.getName());
Callable<Object> deserializer = (Callable<Object>) deserializerClass.getConstructors()[ 0 ].newInstance(serialized);
final Object obj = deserializer.call();
return obj;
}
示例7: initializeClassLoader
import java.net.URLClassLoader; //导入方法依赖的package包/类
@Override
protected void initializeClassLoader() throws Exception {
URL[] urls = new URL[]{
new URL("http://localhost:" + server.getPort() + "/multi-release.jar")
};
cldr = new URLClassLoader(urls);
// load any class, Main is convenient and in the root entries
rootClass = cldr.loadClass("version.Main");
}
示例8: openTemplate
import java.net.URLClassLoader; //导入方法依赖的package包/类
public void openTemplate() {
if (Defaults.getAsBoolean("showTemplateDialog")) {
JOptionPane.showMessageDialog(parent, "Each template has some default values for the parameters. "
+ "Once instantiated you may change them according to your needs.");
Defaults.set("showTemplateDialog", "false");
Defaults.save();
}
int selectedRow = templateTable.getSelectedRow();
if (selectedRow != -1 && templateTable.getRowCount() != 0) {
// close the template panel dialog
SwingUtilities.getWindowAncestor(parent).setVisible(false);
try {
File template = templates[selectedRow].getFile();
File copy = File.createTempFile(template.getName(), "");
FileUtils.copyFile(templates[selectedRow].getFile(), copy);
JarFile templateJarFile = new JarFile(copy);
// get the path of template
Manifest m = templateJarFile.getManifest();
String mainClass = m.getMainAttributes().getValue("Main-Class").toString();
URL url = new URL("file:" + copy.getAbsolutePath());
URLClassLoader myLoader = new URLClassLoader(new URL[] { url }, Thread.currentThread().getContextClassLoader());
Class<?> myClass = myLoader.loadClass(mainClass);
// instantiate the template
myTemp = (ITemplate) myClass.getConstructor(mediator.getClass()).newInstance(mediator);
// shows the input panel of the template
myTemp.showDialog(mediator.getMainWindow());
templateJarFile.close();
myLoader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例9: loadSqlDateUsingNullParent
import java.net.URLClassLoader; //导入方法依赖的package包/类
/**
* Attempt to load a class from the URLClassLoader that references a java.sql.* class. The
* java.sql.* package is one of those not visible to the Java 9 bootstrap class loader that
* was visible to the Java 8 bootstrap class loader.
*/
@Test
public void loadSqlDateUsingNullParent(TestReporter reporter) throws Exception {
URLClassLoader loader = buildLoader(reporter);
Class<?> jsqlUserClass = loader.loadClass("wtf.java9.class_loading.JavaSqlUser");
reporter.publishEntry("Loaded class", jsqlUserClass.toString());
Object jsqlUser = jsqlUserClass.getConstructor().newInstance();
reporter.publishEntry("Created instance", jsqlUser.toString());
loader.close();
}
示例10: doTestUnloadableInStaticFieldIfClosed
import java.net.URLClassLoader; //导入方法依赖的package包/类
private WeakReference<ClassLoader> doTestUnloadableInStaticFieldIfClosed() throws Exception {
final URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader();
final URL[] urls = myLoader.getURLs();
URLClassLoader sepLoader = new URLClassLoader(urls, myLoader.getParent());
Class<?> frqC = FinalizableReferenceQueue.class;
Class<?> sepFrqC = sepLoader.loadClass(frqC.getName());
assertNotSame(frqC, sepFrqC);
Class<?> sepFrqSystemLoaderC =
sepLoader.loadClass(FinalizableReferenceQueue.SystemLoader.class.getName());
Field disabled = sepFrqSystemLoaderC.getDeclaredField("disabled");
disabled.setAccessible(true);
disabled.set(null, true);
Class<?> frqUserC = FrqUser.class;
Class<?> sepFrqUserC = sepLoader.loadClass(frqUserC.getName());
assertNotSame(frqUserC, sepFrqUserC);
assertSame(sepLoader, sepFrqUserC.getClassLoader());
Callable<?> sepFrqUser = (Callable<?>) sepFrqUserC.newInstance();
WeakReference<?> finalizableWeakReference = (WeakReference<?>) sepFrqUser.call();
GcFinalization.awaitClear(finalizableWeakReference);
Field sepFrqUserFinalizedF = sepFrqUserC.getField("finalized");
Semaphore finalizeCount = (Semaphore) sepFrqUserFinalizedF.get(null);
boolean finalized = finalizeCount.tryAcquire(5, TimeUnit.SECONDS);
assertTrue(finalized);
Field sepFrqUserFrqF = sepFrqUserC.getField("frq");
Closeable frq = (Closeable) sepFrqUserFrqF.get(null);
frq.close();
return new WeakReference<ClassLoader>(sepLoader);
}
示例11: testShaderWithStaticInitializedClass
import java.net.URLClassLoader; //导入方法依赖的package包/类
public void testShaderWithStaticInitializedClass()
throws Exception
{
Shader s = newShader();
Set<File> set = new LinkedHashSet<File>();
set.add( new File( "src/test/jars/test-artifact-1.0-SNAPSHOT.jar" ) );
List<Relocator> relocators = new ArrayList<Relocator>();
relocators.add( new SimpleRelocator( "org.apache.maven.plugins.shade", null, null, null ) );
List<ResourceTransformer> resourceTransformers = new ArrayList<ResourceTransformer>();
List<Filter> filters = new ArrayList<Filter>();
File file = new File( "target/testShaderWithStaticInitializedClass.jar" );
ShadeRequest shadeRequest = new ShadeRequest();
shadeRequest.setJars( set );
shadeRequest.setUberJar( file );
shadeRequest.setFilters( filters );
shadeRequest.setRelocators( relocators );
shadeRequest.setResourceTransformers( resourceTransformers );
s.shade( shadeRequest );
URLClassLoader cl = new URLClassLoader( new URL[] { file.toURI().toURL() } );
Class<?> c = cl.loadClass( "hidden.org.apache.maven.plugins.shade.Lib" );
Object o = c.newInstance();
assertEquals( "foo.bar/baz", c.getDeclaredField( "CONSTANT" ).get( o ) );
}
示例12: javaUtilServiceLoaderTest
import java.net.URLClassLoader; //导入方法依赖的package包/类
static boolean javaUtilServiceLoaderTest(URL baseURL,
String serviceClass,
boolean expectToFind,
boolean expectbDotJar,
boolean expectcDotJar) throws IOException {
debug("----------------------------------");
debug("Running test with java.util.ServiceLoader looking for " + serviceClass);
URLClassLoader loader = getLoader(baseURL);
httpServer.reset();
Class<?> messageServiceClass = null;
try {
messageServiceClass = loader.loadClass(serviceClass);
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
throw new RuntimeException("Error in test: " + cnfe);
}
Iterator<?> iterator = (ServiceLoader.load(messageServiceClass, loader)).iterator();
if (expectToFind && !iterator.hasNext()) {
debug(messageServiceClass + " NOT found.");
return false;
}
while (iterator.hasNext()) {
debug("found " + iterator.next() + " " + messageService);
}
debug("HttpServer: " + httpServer);
if (!expectbDotJar && httpServer.bDotJar > 0) {
debug("Unexpeced request sent to the httpserver for b.jar");
return false;
}
if (!expectcDotJar && httpServer.cDotJar > 0) {
debug("Unexpeced request sent to the httpserver for c.jar");
return false;
}
return true;
}
示例13: initializeClassLoader
import java.net.URLClassLoader; //导入方法依赖的package包/类
protected void initializeClassLoader() throws Exception {
URL[] urls = new URL[]{multirelease.toURI().toURL()};
cldr = new URLClassLoader(urls);
// load any class, Main is convenient and in the root entries
rootClass = cldr.loadClass("version.Main");
}
示例14: deserializeWithDependencies
import java.net.URLClassLoader; //导入方法依赖的package包/类
static Object deserializeWithDependencies ( byte[] serialized, final String[] dependencies, final Class<?>[] classDependencies, final Class<?> customDeserializer )
throws Exception {
File[] jars = dependencies.length > 0 ? Maven.resolver().resolve(dependencies).withoutTransitivity().asFile() : new File[0];
URL[] urls = new URL[jars.length];
for ( int i = 0; i < jars.length; i++ ) {
urls[ i ] = jars[ i ].toURI().toURL();
}
URLClassLoader isolatedClassLoader = new URLClassLoader(urls, null) {
{
for ( Class<?> clazz : classDependencies ) {
byte[] classAsBytes = ClassFiles.classAsBytes(clazz);
defineClass(clazz.getName(), classAsBytes, 0, classAsBytes.length);
}
byte[] deserializerClassBytes = ClassFiles.classAsBytes(Deserializer.class);
defineClass(Deserializer.class.getName(), deserializerClassBytes, 0, deserializerClassBytes.length);
if ( customDeserializer != null ) {
try {
Method method = customDeserializer.getMethod("getExtraDependencies");
for ( Class extra : (Class[])method.invoke(null)) {
deserializerClassBytes = ClassFiles.classAsBytes(extra);
defineClass(extra.getName(), deserializerClassBytes, 0, deserializerClassBytes.length);
}
} catch ( NoSuchMethodException e ) { }
deserializerClassBytes = ClassFiles.classAsBytes(customDeserializer);
defineClass(customDeserializer.getName(), deserializerClassBytes, 0, deserializerClassBytes.length);
}
}
};
Class<?> deserializerClass = isolatedClassLoader.loadClass(customDeserializer != null ? customDeserializer.getName() : Deserializer.class.getName());
Callable<Object> deserializer = (Callable<Object>) deserializerClass.getConstructors()[ 0 ].newInstance(serialized);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
try {
// set CCL for Clojure https://groups.google.com/forum/#!topic/clojure/F3ERon6Fye0
Thread.currentThread().setContextClassLoader(isolatedClassLoader);
final Object obj = deserializer.call();
return obj;
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
}
示例15: main
import java.net.URLClassLoader; //导入方法依赖的package包/类
public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
IllegalAccessException, IOException, NoSuchMethodException, InvocationTargetException {
if (args.length != 1) {
throw new Error("Test Bug: Expected GC type wasn't provided as command line argument");
}
GC gc = GC.valueOf(args[0]);
Path wrkDir = Paths.get("");
URL[] url = {wrkDir.toUri().toURL()};
URLClassLoader urlLoader = new URLClassLoader(url);
Class<?> simpleClassLoaderClass = urlLoader.loadClass(SIMPLE_CLASSLOADER_NAME);
ClassLoader simpleClassLoader = (ClassLoader) simpleClassLoaderClass
.getConstructor(java.lang.ClassLoader.class)
.newInstance(TestHumongousClassLoader.class.getClassLoader());
// Sanity check
Asserts.assertEquals(WB.g1IsHumongous(simpleClassLoader), false,
"Test Bug: simpleClassLoader is expected to be non-humongous but it's humongous");
Class<?> humongousClassLoaderClass = simpleClassLoader.loadClass(HUMONGOUS_CLASSLOADER_NAME);
ClassLoader humongousClassLoader = (ClassLoader) humongousClassLoaderClass
.getConstructor(java.lang.ClassLoader.class)
.newInstance(simpleClassLoader);
// Sanity check
Asserts.assertEquals(WB.g1IsHumongous(humongousClassLoader), true,
"Test Bug: humongousClassLoader is expected to be humongous but it's non-humongous");
//Asserts.assertEquals(1,0);
Object[] loadedClasses = new Object[]{
G1SampleClass.LARGEST_NON_HUMONGOUS.getCls(humongousClassLoader, wrkDir, SAMPLE_CLASS_NAME_PREFIX)
.newInstance(),
G1SampleClass.SMALLEST_HUMONGOUS.getCls(humongousClassLoader, wrkDir, SAMPLE_CLASS_NAME_PREFIX)
.newInstance(),
G1SampleClass.ONE_REGION_HUMONGOUS.getCls(humongousClassLoader, wrkDir, SAMPLE_CLASS_NAME_PREFIX)
.newInstance(),
G1SampleClass.TWO_REGION_HUMONGOUS.getCls(humongousClassLoader, wrkDir, SAMPLE_CLASS_NAME_PREFIX)
.newInstance(),
};
// forgetting references to loaded classes
for (int i = 0; i < loadedClasses.length; ++i) {
loadedClasses[i] = null;
}
// forgetting referencies to classloaders
humongousClassLoader = null;
humongousClassLoaderClass = null;
simpleClassLoader = null;
simpleClassLoaderClass = null;
gc.provoke();
// Test checks
Asserts.assertEquals(WB.isClassAlive(HUMONGOUS_CLASSLOADER_NAME), false,
String.format("Classloader class %s is loaded after we forget all references to it",
HUMONGOUS_CLASSLOADER_NAME));
for (G1SampleClass sampleClass : G1SampleClass.values()) {
String className = Helpers.enumNameToClassName(sampleClass.name()) + "Class";
Asserts.assertEquals(WB.isClassAlive(className), false,
String.format("Class %s is loaded after we forget all references to it", className));
}
}