Java Convert Class Names to Class Objects 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 names into a list of Class objects.
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 names to List of Class objects in Java
The Apache Commons Lang library provides the method ClassUtils.convertClassNamesToClasses() to convert the List of String objects into the List of Class objects as the example code below.
ConvertClassNamesToClasses.java
import org.apache.commons.lang3.ClassUtils;
import java.util.ArrayList;
import java.util.List;
public class ConvertClassNamesToClasses {
public static void main(String... args) {
List<String> listOfClassNames = new ArrayList<>();
listOfClassNames.add("java.math.BigDecimal");
listOfClassNames.add("java.util.ArrayList");
listOfClassNames.add("java.util.Date");
listOfClassNames.add("org.apache.commons.lang3.ClassUtils");
List<Class<?>> listOfClasses = ClassUtils.convertClassNamesToClasses(listOfClassNames);
for (Class item : listOfClasses) {
System.out.println(item);
}
}
}
class java.math.BigDecimal
class java.util.ArrayList
class java.util.Date
class org.apache.commons.lang3.ClassUtils
Happy Coding 😊