Java Convert Class Loader to String using Apache Commons Lang

Tags: Apache Commons Apache Commons Lang ClassLoaderUtils Convert ClassLoader URLClassLoader URL String

In this Java tutorial we learn how to convert a ClassLoader or a URLClassLoader to String which presents detailed information of a class loader using the ClassLoaderUtils class of Apache Commons Lang library.

How to add Apache Commons Lang 3 library to your Java project

To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'org.apache.commons:commons-lang3:3.12.0'

To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.12.0</version>
</dependency>

To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/

How to convert Class Loader to String in Java

The Apache Commons Lang library provides the method ClassLoaderUtils.toString() to convert a ClassLoader object or a URLClassLoader object into String value.

The following example code shows you how to use the ClassLoaderUtils.toString() with the ClassLoader object.

ClassLoaderUtilsExample1.java

import org.apache.commons.lang3.ClassLoaderUtils;

public class ClassLoaderUtilsExample1 {
    public static void main(String... args) {
        ClassLoader classLoader = ClassLoaderUtils.class.getClassLoader();

        String result = ClassLoaderUtils.toString(classLoader);

        System.out.println(result);
    }
}
The output is:
sun.misc.Launcher$AppClassLoader@73d16e93[file:/D:/JavaApacheCommonsLang3/build/classes/java/main/, file:/D:/JavaApacheCommonsLang3/build/resources/main, file:/C:/Users/SimpleSolution/.gradle/caches/modules-2/files-2.1/org.apache.commons/commons-lang3/3.12.0/c6842c86792ff03b9f1d1fe2aab8dc23aa6c6f0e/commons-lang3-3.12.0.jar]

The following example code shows you how to use the ClassLoaderUtils.toString() with the URLClassLoader object.

ClassLoaderUtilsExample2.java

import org.apache.commons.lang3.ClassLoaderUtils;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class ClassLoaderUtilsExample2 {
    public static void main(String... args) {
        try {
            URL[] classLoaderUrls = new URL[] {
                    new URL("file:///D:/Data/commons-lang3-3.12.0.jar")
            };

            URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);

            String result = ClassLoaderUtils.toString(urlClassLoader);

            System.out.println(result);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}
The output is:
java.net.URLClassLoader@55f96302[file:/D:/Data/commons-lang3-3.12.0.jar]

Happy Coding 😊