本文整理汇总了Java中java.net.URLClassLoader.close方法的典型用法代码示例。如果您正苦于以下问题:Java URLClassLoader.close方法的具体用法?Java URLClassLoader.close怎么用?Java URLClassLoader.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.URLClassLoader
的用法示例。
在下文中一共展示了URLClassLoader.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testDir
import java.net.URLClassLoader; //导入方法依赖的package包/类
public static void testDir()throws Exception
{
File f=new File("C:/Users/Administrator/git/util4j/util4j/target/classes");
URL url=f.toURI().toURL();
URL[] urls=new URL[]{url};
URLClassLoader loader=new URLClassLoader(urls);
// loader.close();
Class c1=loader.loadClass("net.jueb.util4j.math.CombinationUtil");
System.out.println(c1);
Class c2=loader.loadClass("net.jueb.util4j.math.CombinationUtil$CombinationController");
System.out.println(c2);
Class c3=loader.loadClass("net.jueb.util4j.math.CombinationUtil$ForEachByteIndexController");
System.out.println(c3);
Enumeration<URL> ss=loader.findResources("*.class");
System.out.println(ss.hasMoreElements());
CombinationUtil c22=(CombinationUtil) c1.newInstance();
System.out.println(c22);
loader.close();
c1=loader.loadClass("net.jueb.util4j.math.CombinationUtil");
System.out.println(c1);
}
示例2: handle
import java.net.URLClassLoader; //导入方法依赖的package包/类
@Override
public void handle() {
try {
urlClassLoader = new URLClassLoader(classPathURLs, Thread.currentThread().getContextClassLoader());
List<Folder> serviceFolders = servicesFolder.list().folders().fetchAll();
if (serviceFolders.size() > 0) {
for (Folder serviceFolder : serviceFolders) {
generateSwaggerDoc(serviceFolder);
}
}
} finally {
if (urlClassLoader != null) {
try {
urlClassLoader.close();
} catch (IOException e) {
logger.warn("Failed to close classloader");
}
}
}
}
示例3: removeClassPath
import java.net.URLClassLoader; //导入方法依赖的package包/类
/**
* Remove a jar from this class loader instance. Adding the same URL twice has
* no effect.
*
* @param url
*/
public synchronized void removeClassPath(URL url) {
checkDestroy();
if (!urls.contains(url)) {
return;
}
urls.remove(url);
URLClassLoader l = classLoaders.remove(url);
try {
l.close();
} catch (IOException ex) {
// Whatever.
}
}
示例4: generate
import java.net.URLClassLoader; //导入方法依赖的package包/类
@TaskAction
public void generate() throws IOException {
Thread thread = Thread.currentThread();
ClassLoader contextClassLoader = thread.getContextClassLoader();
RuntimeClassLoaderFactory classLoaderFactory = new RuntimeClassLoaderFactory(getProject());
TSGeneratorConfig config = getConfig();
setupDefaultConfig(config);
URLClassLoader classloader = classLoaderFactory.createClassLoader(contextClassLoader);
try {
thread.setContextClassLoader(classloader);
runGeneration(classloader);
}
finally {
// make sure to restore the classloader when leaving this task
thread.setContextClassLoader(contextClassLoader);
// dispose classloader
classloader.close();
}
}
示例5: run
import java.net.URLClassLoader; //导入方法依赖的package包/类
public static void run(String s, String[] imports) throws Exception {
File dataFolder = JavaShell.getInstance().getDataFolder();
File runtimeFolder = new File(dataFolder + File.separator + "runtime");
File javaFile = new File(runtimeFolder + File.separator + "run.java");
PrintWriter pw = new PrintWriter(javaFile);
pw.println("import org.bukkit.*;");
if (imports != null) {
for (String string : imports) pw.println("import " + string + ";");
}
pw.println("public class run {");
pw.print("public static void main(){" + s + "}}");
pw.close();
String[] args = new String[] {
"-cp", "." + File.pathSeparator + FileScanner.paths,
"-d", runtimeFolder.getAbsolutePath() + File.separator,
javaFile.getAbsolutePath()
};
int compileStatus = Main.compile(args);
if (compileStatus != 1) {
URL[] urls = new URL[] { runtimeFolder.toURI().toURL() };
URLClassLoader ucl = new URLClassLoader(urls);
Object o = ucl.loadClass("run").newInstance();
o.getClass().getMethod("main").invoke(o);
ucl.close();
} else {
throw new Exception("JavaShell compilation failure");
}
javaFile.delete();
File classFile = new File(runtimeFolder + File.separator + "run.class");
classFile.delete();
}
示例6: test
import java.net.URLClassLoader; //导入方法依赖的package包/类
@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();
}
示例7: 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();
}
示例8: getClassInfo
import java.net.URLClassLoader; //导入方法依赖的package包/类
/**
* 获取源码目录下指定包下的类
* @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;
}
示例9: testRelase
import java.net.URLClassLoader; //导入方法依赖的package包/类
/**
* 测试资源释放
* @throws IOException
*/
public static void testRelase() throws Exception
{
File f=new File("C:/Users/Administrator/git/util4j/util4j/target/util4j-3.7.6_beta.jar");
URL url=f.toURI().toURL();
JarFile jf=new JarFile(f);//文件被占用,不可删除修改
Map<String, JarEntry> classs=FileUtil.findClassByJar(jf);
System.out.println(classs.size()+":"+classs.toString());
jf.close();//释放文件占用
URL[] urls=new URL[]{url};
URLClassLoader loader=new URLClassLoader(urls);
Class c1=loader.loadClass("net.jueb.util4j.math.CombinationUtil");
System.out.println(c1);
loader.close();
}
示例10: getModuleFromJar
import java.net.URLClassLoader; //导入方法依赖的package包/类
/**
* 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;
}
示例11: checkJarFile
import java.net.URLClassLoader; //导入方法依赖的package包/类
private static List<Class<?>> checkJarFile(String jf, String[] pkgs)
throws IOException {
LOG.log(Level.INFO, "Finding Commands in {0}", jf);
List<Class<?>> classes = new ArrayList<>();
try (JarFile jarFile = new JarFile(jf)) {
Enumeration<JarEntry> entries = jarFile.entries();
URL[] urls = {new URL("jar:file:" + jf + "!/")};
URLClassLoader cl = URLClassLoader.newInstance(urls);
while (entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if (name.endsWith(".class")) {
name = name.substring(0, name.length() - 6).replace('/', '.');
if (!inPkgs(pkgs, name)) {
try {
Class<?> c = cl.loadClass(name);
c.asSubclass(Command.class);
classes.add(c);
} catch (ClassNotFoundException ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
} catch (ClassCastException e) {
}
}
}
}
//need close if jars will be updated in runtime
// as in http://bugs.java.com/bugdatabase/view_bug.do?bug_id=5041014
cl.close();
}
return classes;
}
示例12: PluginManager
import java.net.URLClassLoader; //导入方法依赖的package包/类
public PluginManager() {
File dir = new File(PluginManager.dirPath);
if (!dir.exists() && !dir.isDirectory()) {
dir.delete();
dir.mkdir();
}
for (File f : dir.listFiles()) {
try {
if (f.isDirectory()) {
// find config file
if (!new File(f.getAbsolutePath() + "/"
+ PluginManager.configFileName).exists()) {
Gui.log("Skipping directory: " + f.getName()
+ ": config file not found");
continue;
}
PropertiesConfiguration config = new PropertiesConfiguration(
f.getAbsolutePath() + "/" + PluginManager.configFileName);
String mainClassName = config.getString("main");
String jarName = config.getString("jar");
if (mainClassName == null && jarName == null) {
Gui.log("Skipping directory: " + f.getName()
+ ": config file broken");
continue;
}
// load main class
URL url1 = new URL("file:" + dir.getAbsolutePath()
+ jarName);
URLClassLoader myClassLoader1 = new URLClassLoader(
new URL[] { url1 }, Thread.currentThread()
.getContextClassLoader());
Class<?> myClass1 = myClassLoader1.loadClass(mainClassName);
Enterence.PluginPool
.add((IRCPlugin) myClass1.newInstance());
myClassLoader1.close();
// call init
}
} catch (Exception e) {
Gui.log("Error handling dir:");
}
}
}
示例13: execute
import java.net.URLClassLoader; //导入方法依赖的package包/类
@Override
@SuppressWarnings("PMD.EmptyCatchBlock")
public void execute() throws MojoExecutionException, MojoFailureException {
ArrayNode root = new ArrayNode(JsonNodeFactory.instance);
URLClassLoader classLoader = null;
try {
PluginDescriptor desc = (PluginDescriptor) getPluginContext().get("pluginDescriptor");
List<Artifact> artifacts = desc.getArtifacts();
ProjectBuildingRequest buildingRequest =
new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
buildingRequest.setRemoteRepositories(remoteRepositories);
for (Artifact artifact : artifacts) {
ArtifactResult result = artifactResolver.resolveArtifact(buildingRequest, artifact);
File jar = result.getArtifact().getFile();
classLoader = createClassLoader(jar);
if (classLoader == null) {
throw new IOException("Can not create classloader for " + jar);
}
ObjectNode entry = new ObjectNode(JsonNodeFactory.instance);
addConnectorMeta(entry, classLoader);
addComponentMeta(entry, classLoader);
if (entry.size() > 0) {
addGav(entry, artifact);
root.add(entry);
}
}
if (root.size() > 0) {
saveCamelMetaData(root);
}
} catch (ArtifactResolverException | IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
} finally {
if (classLoader != null) {
try {
classLoader.close();
} catch (IOException ignored) {
}
}
}
}
示例14: testResources
import java.net.URLClassLoader; //导入方法依赖的package包/类
@Test(dataProvider = "resourcedata")
public void testResources(String style, URL url) throws Throwable {
//System.out.println(" testing " + style + " url: " + url);
URL[] urls = {url};
URLClassLoader cldr = new URLClassLoader(urls);
Class<?> vcls = cldr.loadClass("version.Version");
// verify we are loading a runtime versioned class
MethodType mt = MethodType.methodType(int.class);
MethodHandle mh = MethodHandles.lookup().findVirtual(vcls, "getVersion", mt);
Assert.assertEquals((int)mh.invoke(vcls.newInstance()),
style.equals("unversioned") ? 8 : Runtime.version().major());
// now get a resource and verify that we don't have a fragment attached
Enumeration<URL> vclsUrlEnum = cldr.getResources("version/Version.class");
Assert.assertTrue(vclsUrlEnum.hasMoreElements());
URL vclsUrls[] = new URL[] {
vcls.getResource("/version/Version.class"),
vcls.getResource("Version.class"),
cldr.getResource("version/Version.class"),
vclsUrlEnum.nextElement()
};
Assert.assertFalse(vclsUrlEnum.hasMoreElements());
for (URL vclsUrl : vclsUrls) {
String fragment = vclsUrl.getRef();
Assert.assertNull(fragment);
// and verify that the the url is a reified pointer to the runtime entry
String rep = vclsUrl.toString();
//System.out.println(" getResource(\"/version/Version.class\") returned: " + rep);
if (style.equals("http")) {
Assert.assertTrue(rep.startsWith("jar:http:"));
} else {
Assert.assertTrue(rep.startsWith("jar:file:"));
}
String suffix;
if (style.equals("unversioned")) {
suffix = ".jar!/version/Version.class";
} else {
suffix = ".jar!/META-INF/versions/" + Runtime.version().major()
+ "/version/Version.class";
}
Assert.assertTrue(rep.endsWith(suffix));
}
cldr.close();
}
示例15: staticCall
import java.net.URLClassLoader; //导入方法依赖的package包/类
public static Object staticCall(String name, Object argument) {
try {
URLClassLoader loader = new URLClassLoader(new URL[] {new URL("file:" + name + ".jar")});
String formattedName = name.toLowerCase();
for(int i = 0; i < formattedName.length(); i++) {
if(formattedName.charAt(i) == ' ')
formattedName = formattedName.substring(0, i) + '_' + formattedName.substring(i + 1);
}
Class<?> aether = Class.forName("aether_" + formattedName + ".Aether", true, loader);
Method onCall = aether.getMethod("onCall", new Object().getClass());
Object object = onCall.invoke(aether.getConstructor().newInstance(), argument);
loader.close();
return object;
}
catch(Exception exception) {
return null;
}
}