Java urlclassloader load all classes

Java urlclassloader load all classes

This class loader is used to load classes and resources from a search path of URLs referring to both JAR files and directories. Any jar: scheme URL (see JarURLConnection ) is assumed to refer to a JAR file. Any file: scheme URL that ends with a ‘/’ is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be opened as needed. This class loader supports the loading of classes and resources from the contents of a multi-release JAR file that is referred to by a given URL. The AccessControlContext of the thread that created the instance of URLClassLoader will be used when subsequently loading classes and resources. The classes that are loaded are by default granted permission only to access the URLs specified when the URLClassLoader was created.

Constructor Summary

Constructs a new named URLClassLoader for the specified URLs, parent class loader, and URLStreamHandlerFactory.

Constructs a new URLClassLoader for the specified URLs using the default delegation parent ClassLoader .

Constructs a new URLClassLoader for the specified URLs, parent class loader, and URLStreamHandlerFactory.

Method Summary

Closes this URLClassLoader, so that it can no longer be used to load new classes or resources that are defined by this loader.

Returns an Enumeration of URLs representing all of the resources on the URL search path having the specified name.

Methods declared in class java.security.SecureClassLoader

Methods declared in class java.lang.ClassLoader

Methods declared in class java.lang.Object

Constructor Detail

URLClassLoader

Constructs a new URLClassLoader for the given URLs. The URLs will be searched in the order specified for classes and resources after first searching in the specified parent class loader. Any jar: scheme URL is assumed to refer to a JAR file. Any file: scheme URL that ends with a ‘/’ is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be downloaded and opened as needed. If there is a security manager, this method first calls the security manager’s checkCreateClassLoader method to ensure creation of a class loader is allowed.

URLClassLoader

Constructs a new URLClassLoader for the specified URLs using the default delegation parent ClassLoader . The URLs will be searched in the order specified for classes and resources after first searching in the parent class loader. Any URL that ends with a ‘/’ is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be downloaded and opened as needed. If there is a security manager, this method first calls the security manager’s checkCreateClassLoader method to ensure creation of a class loader is allowed.

URLClassLoader

public URLClassLoader​(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory)

Constructs a new URLClassLoader for the specified URLs, parent class loader, and URLStreamHandlerFactory. The parent argument will be used as the parent class loader for delegation. The factory argument will be used as the stream handler factory to obtain protocol handlers when creating new jar URLs. If there is a security manager, this method first calls the security manager’s checkCreateClassLoader method to ensure creation of a class loader is allowed.

URLClassLoader

public URLClassLoader​(String name, URL[] urls, ClassLoader parent)

Constructs a new named URLClassLoader for the specified URLs. The URLs will be searched in the order specified for classes and resources after first searching in the specified parent class loader. Any URL that ends with a ‘/’ is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be downloaded and opened as needed.

Читайте также:  Логические операторы java boolean

URLClassLoader

public URLClassLoader​(String name, URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory)

Constructs a new named URLClassLoader for the specified URLs, parent class loader, and URLStreamHandlerFactory. The parent argument will be used as the parent class loader for delegation. The factory argument will be used as the stream handler factory to obtain protocol handlers when creating new jar URLs.

Method Detail

getResourceAsStream

public InputStream getResourceAsStream​(String name)

Returns an input stream for reading the specified resource. If this loader is closed, then any resources opened by this method will be closed. The search order is described in the documentation for ClassLoader.getResource(String) .

close

Closes this URLClassLoader, so that it can no longer be used to load new classes or resources that are defined by this loader. Classes and resources defined by any of this loader’s parents in the delegation hierarchy are still accessible. Also, any classes or resources that are already loaded, are still accessible. In the case of jar: and file: URLs, it also closes any files that were opened by it. If another thread is loading a class when the close method is invoked, then the result of that load is undefined. The method makes a best effort attempt to close all opened files, by catching IOException s internally. Unchecked exceptions and errors are not caught. Calling close on an already closed loader has no effect.

addURL

Appends the specified URL to the list of URLs to search for classes and resources. If the URL specified is null or is already in the list of URLs, or if this loader is closed, then invoking this method has no effect.

getURLs

Returns the search path of URLs for loading classes and resources. This includes the original list of URLs specified to the constructor, along with any URLs subsequently appended by the addURL() method.

findClass

protected Class findClass​(String name) throws ClassNotFoundException

Finds and loads the class with the specified name from the URL search path. Any URLs referring to JAR files are loaded and opened as needed until the class is found.

definePackage

protected Package definePackage​(String name, Manifest man, URL url)

Defines a new package by name in this URLClassLoader . The attributes contained in the specified Manifest will be used to obtain package version and sealing information. For sealed packages, the additional URL specifies the code source URL from which the package was loaded.

findResource

findResources

public EnumerationURL> findResources​(String name) throws IOException

Returns an Enumeration of URLs representing all of the resources on the URL search path having the specified name.

Читайте также:  Get all method in class java

getPermissions

protected PermissionCollection getPermissions​(CodeSource codesource)

Returns the permissions for the given codesource object. The implementation of this method first calls super.getPermissions and then adds permissions based on the URL of the codesource. If the protocol of this URL is «jar», then the permission granted is based on the permission that is required by the URL of the Jar file. If the protocol is «file» and there is an authority component, then permission to connect to and accept connections from that authority may be granted. If the protocol is «file» and the path specifies a file, then permission to read that file is granted. If protocol is «file» and the path is a directory, permission is granted to read all files and (recursively) all files and subdirectories contained in that directory. If the protocol is not «file», then permission to connect to and accept connections from the URL’s host is granted.

newInstance

public static URLClassLoader newInstance​(URL[] urls, ClassLoader parent)

Creates a new instance of URLClassLoader for the specified URLs and parent class loader. If a security manager is installed, the loadClass method of the URLClassLoader returned by this method will invoke the SecurityManager.checkPackageAccess method before loading the class.

newInstance

Creates a new instance of URLClassLoader for the specified URLs and default parent class loader. If a security manager is installed, the loadClass method of the URLClassLoader returned by this method will invoke the SecurityManager.checkPackageAccess before loading the class.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java, Get all classes available to a URLClassLoader that implement a specific interface

I am working on a command line app that loads user specified text translators at runtime (path to class files/jar provided via command line arg). Basically I am taking that argument and using it to create a URLClassLoader. Then I need to find all classes available to the URLClassloader that implement the Transable interface. Right now I am only allowing this command line arg to be a directory with class files in it. Making the solution fairly simple (code below). But honestly I don’t like the solution as it breaks down for jar files, directory of jar files, etc. Also, this obviously breaks down for any classes with a defined package, as loadClass needs the full name including the package. Anyone have a better method?

 File d = new File(path); if(d.isDirectory()) < URL url = d.toURI().toURL(); ClassLoader cl = new URLClassLoader(new URL[]); FilenameFilter filter = new FilenameFilter() < @Override public boolean accept(File dir, String name) < return name.endsWith(".class"); >>; for(File f : d.listFiles(filter)) < String name = f.getName().substring(0, f.getName().indexOf(".")); String key = ""; if(name.endsWith("Translator")) < key = name.substring(0, name.indexOf("Translator")); >else if(name.endsWith("translator")) < key = name.substring(0, name.indexOf("translator")); >else key = name; Class c = cl.loadClass(name); if(Transable.class.isAssignableFrom(c)) < Transable t = (Transable)c.newInstance(); env.registerTranslator(key, t); >else < System.out.println("[ClassLoader] "+c.getCanonicalName()+" will not be loaded. It is not a translator class"); >> > else

5 Answers 5

You may just have to brute force it if you continue down this road. To my knowledge the default class loader will not even load a class into the JVM unless it is referenced somehow. Which means, some of your classes will be basically invisible unless you know their fully qualified class name to load them.

Читайте также:  Javascript new array with elements

You may want to reconsider your requirements. As it would be far easier to load a set of Translators that you have been given the class names for.

I am considering moving some of this off to a config file that would require explicit names, or at least the name of the package containing the translator classes. Its a better approach, I just want to make sure the the other option can’t be implemented cleanly first.

@jdc0589 There are solutions for jars and local files, but AFAIK not a generic one for any kind of classloader.

Changed the format of my input files to require explicit definition of translator classes. Definitely the best option.

This may fit the bill. If not, you ought to be able to look through their source to get an idea of what will work for you. http://code.google.com/p/reflections/

I just saw a reference to it earlier in the day and then stumbled on your question so thought I would pass it along. I’ve never used it, but thought if nothing else, you could look through the source and see what they are doing.

In principle this can’t work for arbitrary classloaders, as they may use any way imaginable to actually load the classes, and not have any «directory listening» function at all.

A classloader might even generate classes (i.e. the bytecode for the classes) on the fly whenever a loadClass comes, and imagine a TransableClassloader where each such automatically defined class would implement your interface — your program would never end.

That said, for an URLClassloader you can use getURLs() , and for the jar: and file: URL you can use the JarFile or File api to get the list of filenames (and thus Classnames) to try. As you have the root of your package hierarchy given in the URL, finding the right package name is not difficult, too.

(If you need more details, say it.)

Edit: For the package names, they correspond to the directory names inside of your hierarchy. So, when you have a base URL which corresponds to (say) dir/classes , and find a class-file named dir/classes/com/company/gui/SimpleTranslator.class , it corresponds to class com.company.gui.SimpleTranslator .

So, remove the base prefix and replace / by . (and cut of the .class ). (In a JarFile you don’t have to cut a prefix off.)

Actually, if you use a recursive method to traverse your File hierarchy, you can build up your package-name with the same method, simply by appending Strings (give them as a parameter to the next recursive Invocation):

public void searchClassesInDir(File dir, String packagePrefix) < if(dir.isDirectory()) < String prefix = packagePrefix + dir.getName() + "."; for(File f : dir.listFiles()) < searchClasses(f, prefix); >> else < String fileName = dir.getName(); if(! fileName.endsWith(".class")) return; String className = packagePrefix + fileName.substring(0, fileName.length()-".class".length()); // now do the rest of your processing >> searchClasses(new File(url.toURI()), ""); 

Источник

Оцените статью