-
Notifications
You must be signed in to change notification settings - Fork 53
io microsphere util ClassLoaderUtils
Type: Class | Module: microsphere-java-core | Package: io.microsphere.util | Since: 1.0.0
Source:
microsphere-java-core/src/main/java/io/microsphere/util/ClassLoaderUtils.java
ClassLoader Utility
public abstract class ClassLoaderUtils implements UtilsAuthor: Mercy
-
Introduced in:
1.0.0 -
Current Project Version:
0.1.10-SNAPSHOT
This component is tested and compatible with the following Java versions:
| Java Version | Status |
|---|---|
| Java 8 | ✅ Compatible |
| Java 11 | ✅ Compatible |
| Java 17 | ✅ Compatible |
| Java 21 | ✅ Compatible |
| Java 25 | ✅ Compatible |
int loadedClassCount = ClassLoaderUtils.getLoadedClassCount();
System.out.println("Currently loaded classes: " + loadedClassCount);long unloadedClassCount = ClassLoaderUtils.getUnloadedClassCount();
System.out.println("Total unloaded classes: " + unloadedClassCount);long totalLoadedClassCount = ClassLoaderUtils.getTotalLoadedClassCount();
System.out.println("Total loaded classes: " + totalLoadedClassCount);boolean isVerbose = ClassLoaderUtils.isVerbose();
if (isVerbose) {
System.out.println("JVM is running in verbose class loading mode.");
} else {
System.out.println("Verbose class loading mode is disabled.");
}// Enable verbose class loading output
ClassLoaderUtils.setVerbose(true);
// Disable verbose class loading output
ClassLoaderUtils.setVerbose(false);ClassLoader classLoader = ClassLoaderUtils.getDefaultClassLoader();
if (classLoader != null) {
System.out.println("Using default ClassLoader: " + classLoader);
} else {
System.out.println("No suitable ClassLoader found.");
}// Case 1: Get ClassLoader from a known class
ClassLoader classLoader = ClassLoaderUtils.getClassLoader(MyClass.class);
System.out.println("ClassLoader for MyClass: " + classLoader);// Case 2: Get ClassLoader when no class is provided (uses caller's ClassLoader)
ClassLoader classLoader = ClassLoaderUtils.getClassLoader(null);
System.out.println("Default ClassLoader: " + classLoader);ClassLoader callerClassLoader = ClassLoaderUtils.getCallerClassLoader();
if (callerClassLoader != null) {
System.out.println("Caller ClassLoader: " + callerClassLoader);
} else {
System.out.println("Caller ClassLoader is not available.");
}// Example 1: Find loaded classes with a specific ClassLoader
ClassLoader classLoader = MyClass.class.getClassLoader();
Set<Class<?>> loadedClasses = ClassLoaderUtils.findLoadedClasses(classLoader, "com.example.ClassA", "com.example.ClassB");
System.out.println("Loaded Classes: " + loadedClasses);// Example 2: Use the default ClassLoader to find loaded classes
Set<Class<?>> loadedClasses = ClassLoaderUtils.findLoadedClasses(null, "com.example.ClassC", "com.example.ClassD");
System.out.println("Loaded Classes: " + loadedClasses);// Example 1: Find loaded classes with a specific ClassLoader
ClassLoader classLoader = MyClass.class.getClassLoader();
Iterable<String> classNames = Arrays.asList("com.example.ClassA", "com.example.ClassB");
Set<Class<?>> loadedClasses = ClassLoaderUtils.findLoadedClasses(classLoader, classNames);
System.out.println("Loaded Classes: " + loadedClasses);// Example 2: Use the default ClassLoader to find loaded classes
Iterable<String> classNames = Arrays.asList("com.example.ClassC", "com.example.ClassD");
Set<Class<?>> loadedClasses = ClassLoaderUtils.findLoadedClasses(null, classNames);
System.out.println("Loaded Classes: " + loadedClasses);// Example 1: Check if a class is loaded using a specific ClassLoader
ClassLoader classLoader = MyClass.class.getClassLoader();
boolean isLoaded = ClassLoaderUtils.isLoadedClass(classLoader, MyClass.class);
System.out.println("Is MyClass loaded? " + isLoaded);// Example 2: Use the default ClassLoader to check if a class is loaded
boolean isLoaded = ClassLoaderUtils.isLoadedClass(null, SomeClass.class);
System.out.println("Is SomeClass loaded? " + isLoaded);// Example 1: Check if a class is loaded using a specific ClassLoader
ClassLoader classLoader = MyClass.class.getClassLoader();
boolean isLoaded = ClassLoaderUtils.isLoadedClass(classLoader, "com.example.MyClass");
System.out.println("Is com.example.MyClass loaded? " + isLoaded);// Example 2: Use the default ClassLoader to check if a class is loaded
boolean isLoaded = ClassLoaderUtils.isLoadedClass(null, "com.example.SomeClass");
System.out.println("Is com.example.SomeClass loaded? " + isLoaded);// Example 1: Find a loaded class using a specific ClassLoader
ClassLoader classLoader = MyClass.class.getClassLoader();
String className = "com.example.MyClass";
Class<?> loadedClass = ClassLoaderUtils.findLoadedClass(classLoader, className);
if (loadedClass != null) {
System.out.println(className + " is already loaded.");
} else {
System.out.println(className + " is not loaded yet.");
}// Example 2: Use the default ClassLoader to find a loaded class
String className = "com.example.SomeClass";
Class<?> loadedClass = ClassLoaderUtils.findLoadedClass(null, className);
if (loadedClass != null) {
System.out.println(className + " is already loaded.");
} else {
System.out.println(className + " is not loaded yet.");
}// Example 1: Load a class using a specific ClassLoader
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
Class<?> loadedClass = ClassLoaderUtils.loadClass(customClassLoader, "com.example.MyClass");
if (loadedClass != null) {
System.out.println("Class loaded successfully: " + loadedClass.getName());
} else {
System.out.println("Failed to load class.");
}// Example 2: Use the default ClassLoader to load a class
Class<?> loadedClass = ClassLoaderUtils.loadClass(null, "com.example.AnotherClass");
if (loadedClass != null) {
System.out.println("Class loaded successfully: " + loadedClass.getName());
} else {
System.out.println("Failed to load class.");
}// Example 1: Load a class using a specific ClassLoader without caching
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
Class<?> loadedClass = ClassLoaderUtils.loadClass(customClassLoader, "com.example.MyClass", false);
if (loadedClass != null) {
System.out.println("Class loaded successfully: " + loadedClass.getName());
} else {
System.out.println("Failed to load class.");
}// Example 2: Use the default ClassLoader to load a class with caching enabled
Class<?> loadedClass = ClassLoaderUtils.loadClass(null, "com.example.AnotherClass", true);
if (loadedClass != null) {
System.out.println("Class loaded successfully: " + loadedClass.getName());
} else {
System.out.println("Failed to load class.");
}// Example 1: Get all URLs for a specific resource using a custom ClassLoader
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
ResourceType resourceType = ResourceType.CLASS;
String resourceName = "com.example.MyClass.class";
Set<URL> resourceURLs = ClassLoaderUtils.getResources(customClassLoader, resourceType, resourceName);
System.out.println("Resource URLs: " + resourceURLs);// Example 2: Use the default ClassLoader to get URLs for a resource
ResourceType resourceType = ResourceType.PACKAGE;
String resourceName = "com.example";
Set<URL> resourceURLs = ClassLoaderUtils.getResources(null, resourceType, resourceName);
System.out.println("Resource URLs: " + resourceURLs);// Example 1: Get all URLs for a specific resource using a custom ClassLoader
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
String resourceName = "com.example.MyClass.class";
Set<URL> resourceURLs = ClassLoaderUtils.getResources(customClassLoader, resourceName);
System.out.println("Resource URLs: " + resourceURLs);// Example 2: Use the default ClassLoader to get URLs for a resource
String resourceName = "com.example";
Set<URL> resourceURLs = ClassLoaderUtils.getResources(null, resourceName);
System.out.println("Resource URLs: " + resourceURLs);// Example 1: Retrieve a resource URL using the default ClassLoader
URL resourceUrl = ClassLoaderUtils.getResource("com.example.MyClass.class");
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
} else {
System.out.println("Resource not found.");
}// Example 1: Retrieve a resource URL using a specific ClassLoader
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
String resourceName = "com.example.MyClass.class";
URL resourceUrl = ClassLoaderUtils.getResource(customClassLoader, resourceName);
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
} else {
System.out.println("Resource not found.");
}// Example 2: Use the default ClassLoader to retrieve a resource URL
String resourceName = "com.example.SomeResource.txt";
URL resourceUrl = ClassLoaderUtils.getResource(null, resourceName);
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
} else {
System.out.println("Resource not found.");
}// Example 1: Retrieve a class resource using a specific ClassLoader
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
String className = "com.example.MyClass.class";
URL resourceUrl = ClassLoaderUtils.getResource(customClassLoader, ResourceType.CLASS, className);
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
} else {
System.out.println("Resource not found.");
}// Example 2: Use the default ClassLoader to retrieve a package resource
String packageName = "com.example";
URL resourceUrl = ClassLoaderUtils.getResource(null, ResourceType.PACKAGE, packageName);
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
} else {
System.out.println("Resource not found.");
}// Example 3: Use the default ClassLoader to retrieve a general resource
String resourceName = "config.properties";
URL resourceUrl = ClassLoaderUtils.getResource(null, ResourceType.DEFAULT, resourceName);
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
} else {
System.out.println("Resource not found.");
}Add the following dependency to your pom.xml:
<dependency>
<groupId>io.github.microsphere-projects</groupId>
<artifactId>microsphere-java-core</artifactId>
<version>${microsphere-java.version}</version>
</dependency>Tip: Use the BOM (
microsphere-java-dependencies) for consistent version management. See the Getting Started guide.
import io.microsphere.util.ClassLoaderUtils;| Method | Description |
|---|---|
getLoadedClassCount |
The Method name of ClassLoader#findLoadedClass(String)
|
getUnloadedClassCount |
Returns the total number of classes that have been unloaded since the Java virtual machine has started execution. |
getTotalLoadedClassCount |
Returns the total number of classes that have been loaded since the Java virtual machine has started execution. |
isVerbose |
Checks if the Java virtual machine is currently running with verbose class loading output enabled. |
setVerbose |
Enables or disables the verbose output for the class loading system. |
getDefaultClassLoader |
Retrieves the default ClassLoader to use when none is explicitly provided. |
getClassLoader |
Get the ClassLoader from the loaded class if present. |
getCallerClassLoader |
Retrieves the ClassLoader of the caller class from the call stack. |
findLoadedClasses |
Finds and returns a set of loaded classes for the given class names using the specified ClassLoader. |
findLoadedClasses |
Finds and returns a set of loaded classes for the given class names using the specified ClassLoader. |
isLoadedClass |
Checks if the specified class is already loaded by the given ClassLoader or its parent hierarchy. |
isLoadedClass |
Checks if the specified class name is already loaded by the given ClassLoader or its parent hierarchy. |
findLoadedClass |
Finds a class that has already been loaded by the given ClassLoader or its parent hierarchy. |
loadClass |
Loads the class with the specified name using the provided ClassLoader or the default ClassLoader if none is specified. |
loadClass |
Loads the class with the specified name using the provided ClassLoader or the default ClassLoader if none is specified, |
getResources |
Retrieves a set of URLs representing resources with the specified type and name using the provided ClassLoader. |
getResources |
Retrieves a set of URLs representing resources with the specified name using the provided ClassLoader. |
getResource |
Get the resource URL under specified resource name using the default ClassLoader. |
getResource |
Retrieves a resource URL for the specified resource name using the provided ClassLoader. |
getResource |
Retrieves a resource URL for the specified resource name using the provided ClassLoader and resource type. |
public static int getLoadedClassCount()The Method name of ClassLoader#findLoadedClass(String)
/
private static final String findLoadedClassMethodName = "findLoadedClass";
private static final String classesFieldName = "classes";
protected static final ClassLoadingMXBean classLoadingMXBean = getClassLoadingMXBean();
private static final ConcurrentMap> loadedClassesCache = new ConcurrentHashMap<>(256);
private static final URLClassPathHandle urlClassPathHandle = new ServiceLoadingURLClassPathHandle();
/** Returns the number of classes that are currently loaded in the Java virtual machine.
`int loadedClassCount = ClassLoaderUtils.getLoadedClassCount();
System.out.println("Currently loaded classes: " + loadedClassCount);
`
public static long getUnloadedClassCount()Returns the total number of classes that have been unloaded since the Java virtual machine has started execution.
`long unloadedClassCount = ClassLoaderUtils.getUnloadedClassCount();
System.out.println("Total unloaded classes: " + unloadedClassCount);
`
public static long getTotalLoadedClassCount()Returns the total number of classes that have been loaded since the Java virtual machine has started execution.
`long totalLoadedClassCount = ClassLoaderUtils.getTotalLoadedClassCount();
System.out.println("Total loaded classes: " + totalLoadedClassCount);
`
public static boolean isVerbose()Checks if the Java virtual machine is currently running with verbose class loading output enabled.
This method delegates to the underlying JVM's ClassLoadingMXBean#isVerbose() to determine whether verbose mode is active.
When verbose mode is enabled, the JVM typically prints a message each time a class file is loaded.
`boolean isVerbose = ClassLoaderUtils.isVerbose();
if (isVerbose) {
System.out.println("JVM is running in verbose class loading mode.");
` else {
System.out.println("Verbose class loading mode is disabled.");
}
}
public static void setVerbose(boolean value)Enables or disables the verbose output for the class loading system.
When verbose mode is enabled, the JVM typically prints a message each time a class file is loaded. The verbose output information and the output stream to which it is emitted are implementation-dependent. This method can be called by multiple threads concurrently. Each invocation enables or disables the verbose output globally.
`// Enable verbose class loading output ClassLoaderUtils.setVerbose(true); // Disable verbose class loading output ClassLoaderUtils.setVerbose(false); `
public static ClassLoader getDefaultClassLoader()Retrieves the default ClassLoader to use when none is explicitly provided. This method attempts to find the most appropriate ClassLoader by checking:
- The context ClassLoader of the current thread
- If that's not available, the ClassLoader that loaded this class (
ClassLoaderUtils) - Finally, if neither is available, it falls back to the system ClassLoader
`ClassLoader classLoader = ClassLoaderUtils.getDefaultClassLoader();
if (classLoader != null) {
System.out.println("Using default ClassLoader: " + classLoader);
` else {
System.out.println("No suitable ClassLoader found.");
}
}
public static ClassLoader getClassLoader(@Nullable Class<?> loadedClass)Get the ClassLoader from the loaded class if present.
If the provided loadedClass is null, this method attempts to find the ClassLoader of the caller class using
the specified stack frame depth. If that fails, it falls back to the system ClassLoader.
`// Case 1: Get ClassLoader from a known class
ClassLoader classLoader = ClassLoaderUtils.getClassLoader(MyClass.class);
System.out.println("ClassLoader for MyClass: " + classLoader);
`
`// Case 2: Get ClassLoader when no class is provided (uses caller's ClassLoader)
ClassLoader classLoader = ClassLoaderUtils.getClassLoader(null);
System.out.println("Default ClassLoader: " + classLoader);
`
public static ClassLoader getCallerClassLoader()Retrieves the ClassLoader of the caller class from the call stack.
This method is a convenience wrapper that determines the caller's class by analyzing the call stack, and then returns the associated ClassLoader for that class. It uses a fixed stack frame depth of 4 to identify the caller, which is suitable for most direct usage scenarios.
`ClassLoader callerClassLoader = ClassLoaderUtils.getCallerClassLoader();
if (callerClassLoader != null) {
System.out.println("Caller ClassLoader: " + callerClassLoader);
` else {
System.out.println("Caller ClassLoader is not available.");
}
}
public static Set<Class<?>> findLoadedClasses(@Nullable ClassLoader classLoader, String... classNames)Finds and returns a set of loaded classes for the given class names using the specified ClassLoader.
If the provided ClassLoader is null, it will use the default ClassLoader determined by
#getDefaultClassLoader().
`// Example 1: Find loaded classes with a specific ClassLoader
ClassLoader classLoader = MyClass.class.getClassLoader();
Set> loadedClasses = ClassLoaderUtils.findLoadedClasses(classLoader, "com.example.ClassA", "com.example.ClassB");
System.out.println("Loaded Classes: " + loadedClasses);
`
`// Example 2: Use the default ClassLoader to find loaded classes
Set> loadedClasses = ClassLoaderUtils.findLoadedClasses(null, "com.example.ClassC", "com.example.ClassD");
System.out.println("Loaded Classes: " + loadedClasses);
`
public static Set<Class<?>> findLoadedClasses(@Nullable ClassLoader classLoader, Iterable<String> classNames)Finds and returns a set of loaded classes for the given class names using the specified ClassLoader.
If the provided ClassLoader is null, it will use the default ClassLoader determined by
#getDefaultClassLoader().
`// Example 1: Find loaded classes with a specific ClassLoader
ClassLoader classLoader = MyClass.class.getClassLoader();
Iterable classNames = Arrays.asList("com.example.ClassA", "com.example.ClassB");
Set> loadedClasses = ClassLoaderUtils.findLoadedClasses(classLoader, classNames);
System.out.println("Loaded Classes: " + loadedClasses);
`
`// Example 2: Use the default ClassLoader to find loaded classes
Iterable classNames = Arrays.asList("com.example.ClassC", "com.example.ClassD");
Set> loadedClasses = ClassLoaderUtils.findLoadedClasses(null, classNames);
System.out.println("Loaded Classes: " + loadedClasses);
`
public static boolean isLoadedClass(@Nullable ClassLoader classLoader, Class<?> type)Checks if the specified class is already loaded by the given ClassLoader or its parent hierarchy.
If the provided ClassLoader is null, it will use the default ClassLoader determined by
#getDefaultClassLoader().
`// Example 1: Check if a class is loaded using a specific ClassLoader
ClassLoader classLoader = MyClass.class.getClassLoader();
boolean isLoaded = ClassLoaderUtils.isLoadedClass(classLoader, MyClass.class);
System.out.println("Is MyClass loaded? " + isLoaded);
`
`// Example 2: Use the default ClassLoader to check if a class is loaded
boolean isLoaded = ClassLoaderUtils.isLoadedClass(null, SomeClass.class);
System.out.println("Is SomeClass loaded? " + isLoaded);
`
public static boolean isLoadedClass(@Nullable ClassLoader classLoader, String className)Checks if the specified class name is already loaded by the given ClassLoader or its parent hierarchy.
If the provided ClassLoader is null, it will use the default ClassLoader determined by
#getDefaultClassLoader().
`// Example 1: Check if a class is loaded using a specific ClassLoader
ClassLoader classLoader = MyClass.class.getClassLoader();
boolean isLoaded = ClassLoaderUtils.isLoadedClass(classLoader, "com.example.MyClass");
System.out.println("Is com.example.MyClass loaded? " + isLoaded);
`
`// Example 2: Use the default ClassLoader to check if a class is loaded
boolean isLoaded = ClassLoaderUtils.isLoadedClass(null, "com.example.SomeClass");
System.out.println("Is com.example.SomeClass loaded? " + isLoaded);
`
public static Class<?> findLoadedClass(@Nullable ClassLoader classLoader, String className)Finds a class that has already been loaded by the given ClassLoader or its parent hierarchy.
If the provided ClassLoader is null, it will use the default ClassLoader determined by
#getDefaultClassLoader().
`// Example 1: Find a loaded class using a specific ClassLoader
ClassLoader classLoader = MyClass.class.getClassLoader();
String className = "com.example.MyClass";
Class loadedClass = ClassLoaderUtils.findLoadedClass(classLoader, className);
if (loadedClass != null) {
System.out.println(className + " is already loaded.");
` else {
System.out.println(className + " is not loaded yet.");
}
}
`// Example 2: Use the default ClassLoader to find a loaded class
String className = "com.example.SomeClass";
Class loadedClass = ClassLoaderUtils.findLoadedClass(null, className);
if (loadedClass != null) {
System.out.println(className + " is already loaded.");
` else {
System.out.println(className + " is not loaded yet.");
}
}
public static Class<?> loadClass(@Nullable ClassLoader classLoader, @Nullable String className)Loads the class with the specified name using the provided ClassLoader or the default ClassLoader if none is specified.
This method attempts to load the class using the given ClassLoader. If the ClassLoader is null, it uses the default one determined by
#getDefaultClassLoader(). The actual loading is delegated to the ClassLoader#loadClass(String) method.
`// Example 1: Load a class using a specific ClassLoader
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
Class loadedClass = ClassLoaderUtils.loadClass(customClassLoader, "com.example.MyClass");
if (loadedClass != null) {
System.out.println("Class loaded successfully: " + loadedClass.getName());
` else {
System.out.println("Failed to load class.");
}
}
`// Example 2: Use the default ClassLoader to load a class
Class loadedClass = ClassLoaderUtils.loadClass(null, "com.example.AnotherClass");
if (loadedClass != null) {
System.out.println("Class loaded successfully: " + loadedClass.getName());
` else {
System.out.println("Failed to load class.");
}
}
public static Class<?> loadClass(@Nullable ClassLoader classLoader, @Nullable String className, boolean cached)Loads the class with the specified name using the provided ClassLoader or the default ClassLoader if none is specified, optionally caching the result for faster subsequent lookups.
This method attempts to load the class using the given ClassLoader. If the ClassLoader is null, it uses the default one determined by
#getDefaultClassLoader(). The actual loading is delegated to the ClassLoader#loadClass(String) method.
`// Example 1: Load a class using a specific ClassLoader without caching
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
Class loadedClass = ClassLoaderUtils.loadClass(customClassLoader, "com.example.MyClass", false);
if (loadedClass != null) {
System.out.println("Class loaded successfully: " + loadedClass.getName());
` else {
System.out.println("Failed to load class.");
}
}
`// Example 2: Use the default ClassLoader to load a class with caching enabled
Class loadedClass = ClassLoaderUtils.loadClass(null, "com.example.AnotherClass", true);
if (loadedClass != null) {
System.out.println("Class loaded successfully: " + loadedClass.getName());
` else {
System.out.println("Failed to load class.");
}
}
public static Set<URL> getResources(@Nullable ClassLoader classLoader, @Nonnull ResourceType resourceType, String resourceName)Retrieves a set of URLs representing resources with the specified type and name using the provided ClassLoader.
If the given ClassLoader is null, this method uses the default ClassLoader determined by
#getDefaultClassLoader().
`// Example 1: Get all URLs for a specific resource using a custom ClassLoader
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
ResourceType resourceType = ResourceType.CLASS;
String resourceName = "com.example.MyClass.class";
Set resourceURLs = ClassLoaderUtils.getResources(customClassLoader, resourceType, resourceName);
System.out.println("Resource URLs: " + resourceURLs);
`
`// Example 2: Use the default ClassLoader to get URLs for a resource
ResourceType resourceType = ResourceType.PACKAGE;
String resourceName = "com.example";
Set resourceURLs = ClassLoaderUtils.getResources(null, resourceType, resourceName);
System.out.println("Resource URLs: " + resourceURLs);
`
public static Set<URL> getResources(@Nullable ClassLoader classLoader, String resourceName)Retrieves a set of URLs representing resources with the specified name using the provided ClassLoader.
This method attempts to locate resources across all known ResourceType categories (e.g., CLASS, PACKAGE).
It iterates through each resource type and returns the first non-empty set of URLs it finds. If no matching resources
are found for any type, an empty set is returned.
`// Example 1: Get all URLs for a specific resource using a custom ClassLoader
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
String resourceName = "com.example.MyClass.class";
Set resourceURLs = ClassLoaderUtils.getResources(customClassLoader, resourceName);
System.out.println("Resource URLs: " + resourceURLs);
`
`// Example 2: Use the default ClassLoader to get URLs for a resource
String resourceName = "com.example";
Set resourceURLs = ClassLoaderUtils.getResources(null, resourceName);
System.out.println("Resource URLs: " + resourceURLs);
`
public static URL getResource(String resourceName)Get the resource URL under specified resource name using the default ClassLoader.
This method attempts to locate a resource with the given name by checking various resource types (e.g., CLASS, PACKAGE)
and returns the first matching URL it finds. If no matching resource is found, it returns null.
`// Example 1: Retrieve a resource URL using the default ClassLoader
URL resourceUrl = ClassLoaderUtils.getResource("com.example.MyClass.class");
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
` else {
System.out.println("Resource not found.");
}
}
public static URL getResource(@Nullable ClassLoader classLoader, String resourceName)Retrieves a resource URL for the specified resource name using the provided ClassLoader.
This method attempts to locate a resource by checking various resource types (e.g., CLASS, PACKAGE)
and returns the first matching URL it finds. If no matching resource is found, it returns null.
`// Example 1: Retrieve a resource URL using a specific ClassLoader
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
String resourceName = "com.example.MyClass.class";
URL resourceUrl = ClassLoaderUtils.getResource(customClassLoader, resourceName);
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
` else {
System.out.println("Resource not found.");
}
}
`// Example 2: Use the default ClassLoader to retrieve a resource URL
String resourceName = "com.example.SomeResource.txt";
URL resourceUrl = ClassLoaderUtils.getResource(null, resourceName);
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
` else {
System.out.println("Resource not found.");
}
}
public static URL getResource(@Nullable ClassLoader classLoader, ResourceType resourceType, String resourceName)Retrieves a resource URL for the specified resource name using the provided ClassLoader and resource type.
This method attempts to locate a resource by resolving the resourceName according to the given ResourceType.
If the ClassLoader is null, it uses the default ClassLoader determined by #getDefaultClassLoader().
The resolved resource name is normalized and searched through the provided ClassLoader's ClassLoader#getResource(String) method.
`// Example 1: Retrieve a class resource using a specific ClassLoader
ClassLoader customClassLoader = MyCustomClassLoader.getInstance();
String className = "com.example.MyClass.class";
URL resourceUrl = ClassLoaderUtils.getResource(customClassLoader, ResourceType.CLASS, className);
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
` else {
System.out.println("Resource not found.");
}
}
`// Example 2: Use the default ClassLoader to retrieve a package resource
String packageName = "com.example";
URL resourceUrl = ClassLoaderUtils.getResource(null, ResourceType.PACKAGE, packageName);
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
` else {
System.out.println("Resource not found.");
}
}
`// Example 3: Use the default ClassLoader to retrieve a general resource
String resourceName = "config.properties";
URL resourceUrl = ClassLoaderUtils.getResource(null, ResourceType.DEFAULT, resourceName);
if (resourceUrl != null) {
System.out.println("Resource found at: " + resourceUrl);
` else {
System.out.println("Resource not found.");
}
}
ClassLoader
This documentation was auto-generated from the source code of microsphere-java.
java-annotations
java-core
- ACLLoggerFactory
- AbstractArtifactResourceResolver
- AbstractConverter
- AbstractDeque
- AbstractEventDispatcher
- AbstractLogger
- AbstractURLClassPathHandle
- AccessibleObjectUtils
- AdditionalMetadataResourceConfigurationPropertyLoader
- AnnotationUtils
- ArchiveFileArtifactResourceResolver
- ArrayEnumeration
- ArrayStack
- ArrayUtils
- Artifact
- ArtifactDetector
- ArtifactResourceResolver
- Assert
- BannedArtifactClassLoadingExecutor
- BaseUtils
- BeanMetadata
- BeanProperty
- BeanUtils
- ByteArrayToObjectConverter
- CharSequenceComparator
- CharSequenceUtils
- CharsetUtils
- ClassDataRepository
- ClassDefinition
- ClassFileJarEntryFilter
- ClassFilter
- ClassLoaderUtils
- ClassPathResourceConfigurationPropertyLoader
- ClassPathUtils
- ClassUtils
- ClassicProcessIdResolver
- ClassicURLClassPathHandle
- CollectionUtils
- Compatible
- CompositeSubProtocolURLConnectionFactory
- CompositeURLStreamHandlerFactory
- ConditionalEventListener
- ConfigurationProperty
- ConfigurationPropertyGenerator
- ConfigurationPropertyLoader
- ConfigurationPropertyReader
- Configurer
- ConsoleURLConnection
- Constants
- ConstructorDefinition
- ConstructorUtils
- Converter
- Converters
- CustomizedThreadFactory
- DefaultConfigurationPropertyGenerator
- DefaultConfigurationPropertyReader
- DefaultDeserializer
- DefaultEntry
- DefaultSerializer
- DelegatingBlockingQueue
- DelegatingDeque
- DelegatingIterator
- DelegatingQueue
- DelegatingScheduledExecutorService
- DelegatingURLConnection
- DelegatingURLStreamHandlerFactory
- DelegatingWrapper
- Deprecation
- Deserializer
- Deserializers
- DirectEventDispatcher
- DirectoryFileFilter
- EmptyDeque
- EmptyIterable
- EmptyIterator
- EnumerationIteratorAdapter
- EnumerationUtils
- Event
- EventDispatcher
- EventListener
- ExceptionUtils
- ExecutableDefinition
- ExecutableUtils
- ExecutorUtils
- ExtendableProtocolURLStreamHandler
- FastByteArrayInputStream
- FastByteArrayOutputStream
- FieldDefinition
- FieldUtils
- FileChangedEvent
- FileChangedListener
- FileConstants
- FileExtensionFilter
- FileUtils
- FileWatchService
- Filter
- FilterOperator
- FilterUtils
- FormatUtils
- Functional
- GenericEvent
- GenericEventListener
- Handler
- Handler
- HierarchicalClassComparator
- IOFileFilter
- IOUtils
- ImmutableEntry
- IterableAdapter
- IterableUtils
- Iterators
- JDKLoggerFactory
- JSON
- JSONArray
- JSONException
- JSONObject
- JSONStringer
- JSONTokener
- JSONUtils
- JarEntryFilter
- JarUtils
- JavaType
- JmxUtils
- ListUtils
- Listenable
- Lists
- Logger
- LoggerFactory
- LoggingFileChangedListener
- MBeanAttribute
- MBeanAttributeInfoBuilder
- MBeanConstructorInfoBuilder
- MBeanDescribableBuilder
- MBeanExecutableInfoBuilder
- MBeanFeatureInfoBuilder
- MBeanInfoBuilder
- MBeanNotificationInfoBuilder
- MBeanOperationInfoBuilder
- MBeanParameterInfoBuilder
- ManagementUtils
- ManifestArtifactResourceResolver
- MapToPropertiesConverter
- MapUtils
- Maps
- MavenArtifact
- MavenArtifactResourceResolver
- MemberDefinition
- MemberUtils
- MetadataResourceConfigurationPropertyLoader
- MethodDefinition
- MethodHandleUtils
- MethodHandlesLookupUtils
- MethodUtils
- ModernProcessIdResolver
- ModernURLClassPathHandle
- Modifier
- MultiValueConverter
- MultipleType
- MutableInteger
- MutableURLStreamHandlerFactory
- NameFileFilter
- NoOpLogger
- NoOpLoggerFactory
- NoOpURLClassPathHandle
- NumberToByteConverter
- NumberToCharacterConverter
- NumberToDoubleConverter
- NumberToFloatConverter
- NumberToIntegerConverter
- NumberToLongConverter
- NumberToShortConverter
- NumberUtils
- ObjectToBooleanConverter
- ObjectToByteArrayConverter
- ObjectToByteConverter
- ObjectToCharacterConverter
- ObjectToDoubleConverter
- ObjectToFloatConverter
- ObjectToIntegerConverter
- ObjectToLongConverter
- ObjectToOptionalConverter
- ObjectToShortConverter
- ObjectToStringConverter
- PackageNameClassFilter
- PackageNameClassNameFilter
- ParallelEventDispatcher
- ParameterizedTypeImpl
- PathConstants
- Predicates
- Prioritized
- PriorityComparator
- ProcessExecutor
- ProcessIdResolver
- ProcessManager
- PropertiesToStringConverter
- PropertiesUtils
- PropertyConstants
- PropertyResourceBundleControl
- PropertyResourceBundleUtils
- ProtocolConstants
- ProxyUtils
- QueueUtils
- ReadOnlyIterator
- ReflectionUtils
- ReflectiveConfigurationPropertyGenerator
- ReflectiveDefinition
- ResourceConstants
- ReversedDeque
- Scanner
- SecurityUtils
- SeparatorConstants
- Serializer
- Serializers
- ServiceLoaderURLStreamHandlerFactory
- ServiceLoaderUtils
- ServiceLoadingURLClassPathHandle
- SetUtils
- Sets
- Sfl4jLoggerFactory
- ShutdownHookCallbacksThread
- ShutdownHookUtils
- SimpleClassScanner
- SimpleFileScanner
- SimpleJarEntryScanner
- SingletonDeque
- SingletonEnumeration
- SingletonIterator
- StackTraceUtils
- StandardFileWatchService
- StandardURLStreamHandlerFactory
- StopWatch
- StreamArtifactResourceResolver
- Streams
- StringBuilderWriter
- StringConverter
- StringDeserializer
- StringSerializer
- StringToArrayConverter
- StringToBlockingDequeConverter
- StringToBlockingQueueConverter
- StringToBooleanConverter
- StringToByteConverter
- StringToCharArrayConverter
- StringToCharacterConverter
- StringToClassConverter
- StringToCollectionConverter
- StringToDequeConverter
- StringToDoubleConverter
- StringToDurationConverter
- StringToFloatConverter
- StringToInputStreamConverter
- StringToIntegerConverter
- StringToIterableConverter
- StringToListConverter
- StringToLongConverter
- StringToMultiValueConverter
- StringToNavigableSetConverter
- StringToQueueConverter
- StringToSetConverter
- StringToShortConverter
- StringToSortedSetConverter
- StringToStringConverter
- StringToTransferQueueConverter
- StringUtils
- SubProtocolURLConnectionFactory
- SymbolConstants
- SystemUtils
- ThrowableAction
- ThrowableBiConsumer
- ThrowableBiFunction
- ThrowableConsumer
- ThrowableFunction
- ThrowableSupplier
- ThrowableUtils
- TrueClassFilter
- TrueFileFilter
- TypeArgument
- TypeFinder
- TypeUtils
- URLClassPathHandle
- URLUtils
- UnmodifiableDeque
- UnmodifiableIterator
- UnmodifiableQueue
- Utils
- ValueHolder
- Version
- VersionUtils
- VirtualMachineProcessIdResolver
- Wrapper
- WrapperProcessor
jdk-tools
lang-model
- AnnotatedElementJSONElementVisitor
- AnnotationUtils
- ClassUtils
- ConstructorUtils
- ElementUtils
- ExecutableElementComparator
- FieldUtils
- JSONAnnotationValueVisitor
- JSONElementVisitor
- LoggerUtils
- MemberUtils
- MessagerUtils
- MethodUtils
- ResolvableAnnotationValueVisitor
- StringAnnotationValue
- TypeUtils
annotation-processor
- ConfigurationPropertyAnnotationProcessor
- ConfigurationPropertyJSONElementVisitor
- FilerProcessor
- ResourceProcessor
java-test
- AbstractAnnotationProcessingTest
- Ancestor
- AnnotationProcessingTestProcessor
- ArrayTypeModel
- CollectionTypeModel
- Color
- CompilerInvocationInterceptor
- ConfigurationPropertyModel
- DefaultTestService
- GenericTestService
- MapTypeModel
- Model
- Parent
- PrimitiveTypeModel
- SimpleTypeModel
- StringArrayList
- TestAnnotation
- TestService
- TestServiceImpl