Java Convert Class Objects to Class Names using Apache Commons Lang

Tags: ClassUtils Apache Commons Apache Commons Lang Class Convert

This Java tutorial shows you how to use the ClassUtils utility class of Apache Commons Lang library to convert a list of Class objects into a list of class names.

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 List of Class objects to List of class names in Java

The Apache Commons Lang library provides the method ClassUtils.convertClassesToClassNames() to convert the List of Class objects into List of String objects as the example code below.

ConvertClassesToClassNames.java

import org.apache.commons.lang3.ClassUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ConvertClassesToClassNames {
    public static void main(String... args) {
        List<Class<?>> listOfClasses = new ArrayList<>();
        listOfClasses.add(BigDecimal.class);
        listOfClasses.add(Double.class);
        listOfClasses.add(Date.class);

        List<String> listOfClassNames = ClassUtils.convertClassesToClassNames(listOfClasses);

        for (String item : listOfClassNames) {
            System.out.println(item);
        }
    }
}
The output is:
java.math.BigDecimal
java.lang.Double
java.util.Date

Happy Coding 😊