-
Notifications
You must be signed in to change notification settings - Fork 0
ClassUtils
Utilities for Class
objects are available in ClassUtils
. This page lists a few of the features.
Classes can be loaded and checked for existence with ClassUtils#classExists
, ClassUtils#tryLoadClass
and ClassUtils#loadClassOrThrow
. These methods exist as wrappers around Class#forName
and are added for convenience so you don't have to deal with the checked exceptions.
ClassUtils#getClassName
allows you to get the class name null-safely. To get a short, user-friendly name for all classes, you can use ClassUtils#getSemanticName
. This method is intended as an alternative to Class#getSimpleName
, which sometimes produces no output, or output that makes it impossible to identify the class even for humans.
Class | Class#getSimpleName | ClassUtils#getSemanticName |
---|---|---|
int[].class |
"int[]" |
"int[]" |
Map.Entry.class |
"Entry" |
"Map$Entry" |
new Object() { }.getClass() |
"" (empty string) |
"ParentClass$1" |
null |
NPE | "null" |
Avoid checked errors by using ClassUtils#asSubclassIfPossible
:
void storeClass(Class<? extends Serializable> clazz) { ... }
ClassUtils.asSubclassIfPossible(clazz, Serializable.class)
.ifPresent(subclass -> storeClass(subclass));
Plain Java:
if (Serializable.class.isAssignableFrom(clazz)) {
storeClass((Class) clazz); // Unchecked warning
}
Note: to find out if a class is an enum, use EnumUtils#asEnumClassIfPossible instead.
ClassUtils#getType(Class)
returns an entry of the enum ClassType
to describe what kind of class was input: e.g., ClassUtils.getType(Serializable.class)
returns INTERFACE
, ClassUtils.getType(Override.class)
returns ANNOTATION
. Before you inspect a class, you may want to make sure that a class is of the desired type.
To process classes differently based on their type, you can use ClassUtils#processClassByType
. It takes a ClassTypeCallback
that you implement, where you can define behavior for each class type:
ClassTypeCallback<String> callback = new ClassTypeCallback<String>() {
@Override
public String forEnum(Class<? extends Enum<?>> enumClass) {
return "enum[" + enumClass.getSimpleName() + "]";
}
@Override
public String forAnnotation(Class<? extends Annotation> annotationClass) {
return "@" + annotationClass.getSimpleName();
}
};
System.out.println(ClassUtils.processClassByType(TimeUnit.class, callback)); // enum[TimeUnit]
System.out.println(ClassUtils.processClassByType(Override.class, callback)); // @Override
System.out.println(ClassUtils.processClassByType(int[].class, callback)); // null (method for ARRAY not overridden)
Documentation
Internal (for development)