Class ClassUtil
- java.lang.Object
-
- com.fasterxml.jackson.databind.util.ClassUtil
-
public final class ClassUtil extends Object
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
ClassUtil.Ctor
Value class used for caching Constructor declarations; used because caching done by JDK appears to be somewhat inefficient for some use cases.
-
Constructor Summary
Constructors Constructor Description ClassUtil()
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static String
apostrophed(String text)
Returns either'text'
(single-quoted) or[null]
.static String
backticked(String text)
Returns either`text`
(backtick-quoted) or[null]
.static String
canBeABeanType(Class<?> type)
static void
checkAndFixAccess(Member member)
Deprecated.Since 2.7 call variant that takes boolean flag.static void
checkAndFixAccess(Member member, boolean evenIfAlreadyPublic)
Method that is called if aMember
may need forced access, to force a field, method or constructor to be accessible: this is done by callingAccessibleObject.setAccessible(boolean)
.static String
classNameOf(Object inst)
Helper method used to construct appropriate description when passed either type (Class) or an instance; in latter case, class of instance is to be used.static Class<?>
classOf(Object inst)
static void
closeOnFailAndThrowAsIOE(JsonGenerator g, Closeable toClose, Exception fail)
Helper method that encapsulate logic in trying to close givenCloseable
in case of failure; useful mostly in forcing flush()ing as otherwise error conditions tend to be hard to diagnose.static void
closeOnFailAndThrowAsIOE(JsonGenerator g, Exception fail)
Helper method that encapsulate logic in trying to close output generator in case of failure; useful mostly in forcing flush()ing as otherwise error conditions tend to be hard to diagnose.static <T> T
createInstance(Class<T> cls, boolean canFixAccess)
Method that can be called to try to create an instantiate of specified type.static Object
defaultValue(Class<?> cls)
Helper method used to get default value for wrappers used for primitive types (0 for Integer etc)static <T> Iterator<T>
emptyIterator()
static String
exceptionMessage(Throwable t)
Helper method that returnsThrowable.getMessage()
for all other exceptions except for (a)JacksonException
, for whichgetOriginalMessage()
is returned, and (b)InvocationTargetException
, for which the cause's message is returned, if available.static Annotation[]
findClassAnnotations(Class<?> cls)
static <T> Constructor<T>
findConstructor(Class<T> cls, boolean forceAccess)
static Class<? extends Enum<?>>
findEnumType(Class<?> cls)
Helper method that can be used to dynamically figure out formal enumeration type (class) for given class of an enumeration value.static Class<? extends Enum<?>>
findEnumType(Enum<?> en)
Helper method that can be used to dynamically figure out formal enumeration type (class) for given enumeration.static Class<? extends Enum<?>>
findEnumType(EnumMap<?,?> m)
Helper method that can be used to dynamically figure out enumeration type of givenEnumSet
, without having access to its declaration.static Class<? extends Enum<?>>
findEnumType(EnumSet<?> s)
Helper method that can be used to dynamically figure out enumeration type of givenEnumSet
, without having access to its declaration.static <T extends Annotation>
Enum<?>findFirstAnnotatedEnumValue(Class<Enum<?>> enumClass, Class<T> annotationClass)
A method that will look for the first Enum value annotated with the given Annotation.static List<Class<?>>
findRawSuperTypes(Class<?> cls, Class<?> endBefore, boolean addClassItself)
static List<Class<?>>
findSuperClasses(Class<?> cls, Class<?> endBefore, boolean addClassItself)
Method for finding all super classes (but not super interfaces) of given class, starting with the immediate super class and ending in the most distant one.static List<JavaType>
findSuperTypes(JavaType type, Class<?> endBefore, boolean addClassItself)
Method that will find all sub-classes and implemented interfaces of a given class or interface.static List<Class<?>>
findSuperTypes(Class<?> cls, Class<?> endBefore)
Deprecated.static List<Class<?>>
findSuperTypes(Class<?> cls, Class<?> endBefore, List<Class<?>> result)
Deprecated.static String
getClassDescription(Object classOrInstance)
Helper method used to construct appropriate description when passed either type (Class) or an instance; in latter case, class of instance is to be used.static Method[]
getClassMethods(Class<?> cls)
Helper method that gets methods declared in given class; usually a simple thing, but sometimes (as per [databind#785]) more complicated, depending on classloader setup.static ClassUtil.Ctor[]
getConstructors(Class<?> cls)
static Field[]
getDeclaredFields(Class<?> cls)
Deprecated.since 2.11 (just call Class method directly)static Method[]
getDeclaredMethods(Class<?> cls)
Deprecated.since 2.11 (just call Class method directly)static Class<?>
getDeclaringClass(Class<?> cls)
static Class<?>
getEnclosingClass(Class<?> cls)
static Type[]
getGenericInterfaces(Class<?> cls)
static Type
getGenericSuperclass(Class<?> cls)
static Class<?>
getOuterClass(Class<?> type)
Method for finding enclosing class for non-static inner classesstatic String
getPackageName(Class<?> cls)
Deprecated.Since 2.12 (just call methods directly or check class name)static Throwable
getRootCause(Throwable t)
Method that can be used to find the "root cause", innermost of chained (wrapped) exceptions.static String
getTypeDescription(JavaType fullType)
Helper method to create and return "backticked" description of given resolved type (or,"null"
ifnull
passed), similar to return vaue ofgetClassDescription(Object)
.static boolean
hasClass(Object inst, Class<?> raw)
static boolean
hasEnclosingMethod(Class<?> cls)
static boolean
hasGetterSignature(Method m)
Deprecated.Since 2.6 not used; may be removed before 3.xstatic boolean
isBogusClass(Class<?> cls)
static boolean
isCollectionMapOrArray(Class<?> type)
static boolean
isConcrete(Class<?> type)
Helper method that checks if given class is a concrete one; that is, not an interface or abstract class.static boolean
isConcrete(Member member)
static boolean
isEnumType(Class<?> rawType)
Helper method that encapsulates reliable check on whether given raw type "is an Enum", that is, is or extendsEnum
.static boolean
isJacksonStdImpl(Class<?> implClass)
static boolean
isJacksonStdImpl(Object impl)
Method that can be called to determine if given Object is the default implementation Jackson uses; as opposed to a custom serializer installed by a module or calling application.static boolean
isJDKClass(Class<?> rawType)
Accessor for checking whether givenClass
is under Java package ofjava.*
orjavax.*
(including all sub-packages).static String
isLocalType(Class<?> type, boolean allowNonStatic)
static boolean
isNonStaticInnerClass(Class<?> cls)
static boolean
isObjectOrPrimitive(Class<?> cls)
static boolean
isProxyType(Class<?> type)
Helper method used to weed out dynamic Proxy types; types that do not expose concrete method API that we could use to figure out automatic Bean (property) based serialization.static boolean
isRecordType(Class<?> cls)
Helper method for detecting Java14-added newRecord
typesstatic String
name(PropertyName name)
Returns either single-quoted (apostrophe)'name'
(ifname
not null), or "[null]" ifname
is null.static String
name(String name)
Returns either single-quoted (apostrophe)'name'
(ifname
not null), or "[null]" ifname
is null.static String
nameOf(Named named)
Returns either single-quoted (apostrophe)'named.getName()'
(ifnamed
not null), or "[null]" ifnamed
is null.static String
nameOf(Class<?> cls)
Returns either `cls.getName()` (if `cls` not null), or "[null]" if `cls` is null.static <T> T
nonNull(T valueOrNull, T defaultValue)
static String
nonNullString(String str)
static String
nullOrToString(Object value)
static Class<?>
primitiveType(Class<?> type)
Method that can be used to find primitive type for given class if (but only if) it is either wrapper type or primitive type; returnsnull
if type is neither.static String
quotedOr(Object str, String forNull)
Returns either quoted value (with double-quotes) -- if argument non-null String -- or String NULL (no quotes) (if null).static Class<?>
rawClass(JavaType t)
static void
throwAsIAE(Throwable t)
Method that will wrap 't' as anIllegalArgumentException
if it is a checked exception; otherwise (runtime exception or error) throw as isstatic void
throwAsIAE(Throwable t, String msg)
Method that will wrap 't' as anIllegalArgumentException
(and with specified message) if it is a checked exception; otherwise (runtime exception or error) throw as isstatic <T> T
throwAsMappingException(DeserializationContext ctxt, IOException e0)
static Throwable
throwIfError(Throwable t)
Helper method that will check if argument is anError
, and if so, (re)throw it; otherwise just returnstatic Throwable
throwIfIOE(Throwable t)
Helper method that will check if argument is anIOException
, and if so, (re)throw it; otherwise just returnstatic Throwable
throwIfRTE(Throwable t)
Helper method that will check if argument is anRuntimeException
, and if so, (re)throw it; otherwise just returnstatic Throwable
throwRootCauseIfIOE(Throwable t)
Method that works like by callinggetRootCause(java.lang.Throwable)
and then either throwing it (if instanceofIOException
), or return.static void
unwrapAndThrowAsIAE(Throwable t)
Method that will locate the innermost exception for given Throwable; and then wrap it as anIllegalArgumentException
if it is a checked exception; otherwise (runtime exception or error) throw as isstatic void
unwrapAndThrowAsIAE(Throwable t, String msg)
Method that will locate the innermost exception for given Throwable; and then wrap it as anIllegalArgumentException
if it is a checked exception; otherwise (runtime exception or error) throw as isstatic void
verifyMustOverride(Class<?> expType, Object instance, String method)
static Class<?>
wrapperType(Class<?> primitiveType)
Helper method for finding wrapper type for given primitive type (why isn't there one in JDK?).
-
-
-
Method Detail
-
emptyIterator
public static <T> Iterator<T> emptyIterator()
- Since:
- 2.7
-
findSuperTypes
public static List<JavaType> findSuperTypes(JavaType type, Class<?> endBefore, boolean addClassItself)
Method that will find all sub-classes and implemented interfaces of a given class or interface. Classes are listed in order of precedence, starting with the immediate super-class, followed by interfaces class directly declares to implemented, and then recursively followed by parent of super-class and so forth. Note thatObject.class
is not included in the list regardless of whetherendBefore
argument is defined or not.- Parameters:
endBefore
- Super-type to NOT include in results, if any; when encountered, will be ignored (and no super types are checked).- Since:
- 2.7
-
findRawSuperTypes
public static List<Class<?>> findRawSuperTypes(Class<?> cls, Class<?> endBefore, boolean addClassItself)
- Since:
- 2.7
-
findSuperClasses
public static List<Class<?>> findSuperClasses(Class<?> cls, Class<?> endBefore, boolean addClassItself)
Method for finding all super classes (but not super interfaces) of given class, starting with the immediate super class and ending in the most distant one. Class itself is included ifaddClassItself
is true.NOTE: mostly/only called to resolve mix-ins as that's where we do not care about fully-resolved types, just associated annotations.
- Since:
- 2.7
-
findSuperTypes
@Deprecated public static List<Class<?>> findSuperTypes(Class<?> cls, Class<?> endBefore)
Deprecated.
-
findSuperTypes
@Deprecated public static List<Class<?>> findSuperTypes(Class<?> cls, Class<?> endBefore, List<Class<?>> result)
Deprecated.
-
canBeABeanType
public static String canBeABeanType(Class<?> type)
- Returns:
- Null if class might be a bean; type String (that identifies why it's not a bean) if not
-
getOuterClass
public static Class<?> getOuterClass(Class<?> type)
Method for finding enclosing class for non-static inner classes
-
isProxyType
public static boolean isProxyType(Class<?> type)
Helper method used to weed out dynamic Proxy types; types that do not expose concrete method API that we could use to figure out automatic Bean (property) based serialization.
-
isConcrete
public static boolean isConcrete(Class<?> type)
Helper method that checks if given class is a concrete one; that is, not an interface or abstract class.
-
isConcrete
public static boolean isConcrete(Member member)
-
isCollectionMapOrArray
public static boolean isCollectionMapOrArray(Class<?> type)
-
isBogusClass
public static boolean isBogusClass(Class<?> cls)
-
isRecordType
public static boolean isRecordType(Class<?> cls)
Helper method for detecting Java14-added newRecord
types- Since:
- 2.12
-
isObjectOrPrimitive
public static boolean isObjectOrPrimitive(Class<?> cls)
- Since:
- 2.7
-
verifyMustOverride
public static void verifyMustOverride(Class<?> expType, Object instance, String method)
- Since:
- 2.9
-
hasGetterSignature
@Deprecated public static boolean hasGetterSignature(Method m)
Deprecated.Since 2.6 not used; may be removed before 3.x
-
throwIfError
public static Throwable throwIfError(Throwable t)
Helper method that will check if argument is anError
, and if so, (re)throw it; otherwise just return- Since:
- 2.9
-
throwIfRTE
public static Throwable throwIfRTE(Throwable t)
Helper method that will check if argument is anRuntimeException
, and if so, (re)throw it; otherwise just return- Since:
- 2.9
-
throwIfIOE
public static Throwable throwIfIOE(Throwable t) throws IOException
Helper method that will check if argument is anIOException
, and if so, (re)throw it; otherwise just return- Throws:
IOException
- Since:
- 2.9
-
getRootCause
public static Throwable getRootCause(Throwable t)
Method that can be used to find the "root cause", innermost of chained (wrapped) exceptions.
-
throwRootCauseIfIOE
public static Throwable throwRootCauseIfIOE(Throwable t) throws IOException
Method that works like by callinggetRootCause(java.lang.Throwable)
and then either throwing it (if instanceofIOException
), or return.- Throws:
IOException
- Since:
- 2.8
-
throwAsIAE
public static void throwAsIAE(Throwable t)
Method that will wrap 't' as anIllegalArgumentException
if it is a checked exception; otherwise (runtime exception or error) throw as is
-
throwAsIAE
public static void throwAsIAE(Throwable t, String msg)
Method that will wrap 't' as anIllegalArgumentException
(and with specified message) if it is a checked exception; otherwise (runtime exception or error) throw as is
-
throwAsMappingException
public static <T> T throwAsMappingException(DeserializationContext ctxt, IOException e0) throws JsonMappingException
- Throws:
JsonMappingException
- Since:
- 2.9
-
unwrapAndThrowAsIAE
public static void unwrapAndThrowAsIAE(Throwable t)
Method that will locate the innermost exception for given Throwable; and then wrap it as anIllegalArgumentException
if it is a checked exception; otherwise (runtime exception or error) throw as is
-
unwrapAndThrowAsIAE
public static void unwrapAndThrowAsIAE(Throwable t, String msg)
Method that will locate the innermost exception for given Throwable; and then wrap it as anIllegalArgumentException
if it is a checked exception; otherwise (runtime exception or error) throw as is
-
closeOnFailAndThrowAsIOE
public static void closeOnFailAndThrowAsIOE(JsonGenerator g, Exception fail) throws IOException
Helper method that encapsulate logic in trying to close output generator in case of failure; useful mostly in forcing flush()ing as otherwise error conditions tend to be hard to diagnose. However, it is often the case that output state may be corrupt so we need to be prepared for secondary exception without masking original one.- Throws:
IOException
- Since:
- 2.8
-
closeOnFailAndThrowAsIOE
public static void closeOnFailAndThrowAsIOE(JsonGenerator g, Closeable toClose, Exception fail) throws IOException
Helper method that encapsulate logic in trying to close givenCloseable
in case of failure; useful mostly in forcing flush()ing as otherwise error conditions tend to be hard to diagnose. However, it is often the case that output state may be corrupt so we need to be prepared for secondary exception without masking original one.- Throws:
IOException
- Since:
- 2.8
-
createInstance
public static <T> T createInstance(Class<T> cls, boolean canFixAccess) throws IllegalArgumentException
Method that can be called to try to create an instantiate of specified type. Instantiation is done using default no-argument constructor.- Parameters:
canFixAccess
- Whether it is possible to try to change access rights of the default constructor (in case it is not publicly accessible) or not.- Throws:
IllegalArgumentException
- If instantiation fails for any reason; except for cases where constructor throws an unchecked exception (which will be passed as is)
-
findConstructor
public static <T> Constructor<T> findConstructor(Class<T> cls, boolean forceAccess) throws IllegalArgumentException
- Throws:
IllegalArgumentException
-
nonNull
public static <T> T nonNull(T valueOrNull, T defaultValue)
- Since:
- 2.9
-
quotedOr
public static String quotedOr(Object str, String forNull)
Returns either quoted value (with double-quotes) -- if argument non-null String -- or String NULL (no quotes) (if null).- Since:
- 2.9
-
getClassDescription
public static String getClassDescription(Object classOrInstance)
Helper method used to construct appropriate description when passed either type (Class) or an instance; in latter case, class of instance is to be used.
-
getTypeDescription
public static String getTypeDescription(JavaType fullType)
Helper method to create and return "backticked" description of given resolved type (or,"null"
ifnull
passed), similar to return vaue ofgetClassDescription(Object)
.- Parameters:
fullType
- Fully resolved type or null- Returns:
- String description of type including generic type parameters, surrounded by backticks, if type passed; or string "null" if {code null} passed
- Since:
- 2.10
-
classNameOf
public static String classNameOf(Object inst)
Helper method used to construct appropriate description when passed either type (Class) or an instance; in latter case, class of instance is to be used.- Since:
- 2.9
-
nameOf
public static String nameOf(Class<?> cls)
Returns either `cls.getName()` (if `cls` not null), or "[null]" if `cls` is null.- Since:
- 2.9
-
nameOf
public static String nameOf(Named named)
Returns either single-quoted (apostrophe)'named.getName()'
(ifnamed
not null), or "[null]" ifnamed
is null.NOTE: before 2.12 returned "backticked" version instead of single-quoted name; changed to be compatible with most existing quoting usage within databind
- Since:
- 2.9
-
name
public static String name(String name)
Returns either single-quoted (apostrophe)'name'
(ifname
not null), or "[null]" ifname
is null.- Since:
- 2.12
-
name
public static String name(PropertyName name)
Returns either single-quoted (apostrophe)'name'
(ifname
not null), or "[null]" ifname
is null.- Since:
- 2.12
-
backticked
public static String backticked(String text)
Returns either`text`
(backtick-quoted) or[null]
.- Since:
- 2.9
-
apostrophed
public static String apostrophed(String text)
Returns either'text'
(single-quoted) or[null]
.- Since:
- 2.9
-
exceptionMessage
public static String exceptionMessage(Throwable t)
Helper method that returnsThrowable.getMessage()
for all other exceptions except for (a)JacksonException
, for whichgetOriginalMessage()
is returned, and (b)InvocationTargetException
, for which the cause's message is returned, if available. Method is used to avoid accidentally including trailing location information twice in message when wrapping exceptions.- Since:
- 2.9.7
-
defaultValue
public static Object defaultValue(Class<?> cls)
Helper method used to get default value for wrappers used for primitive types (0 for Integer etc)
-
wrapperType
public static Class<?> wrapperType(Class<?> primitiveType)
Helper method for finding wrapper type for given primitive type (why isn't there one in JDK?). NOTE: throwsIllegalArgumentException
if given type is NOT primitive type (caller has to check).
-
primitiveType
public static Class<?> primitiveType(Class<?> type)
Method that can be used to find primitive type for given class if (but only if) it is either wrapper type or primitive type; returnsnull
if type is neither.- Since:
- 2.7
-
checkAndFixAccess
@Deprecated public static void checkAndFixAccess(Member member)
Deprecated.Since 2.7 call variant that takes boolean flag.Equivalent to call:checkAndFixAccess(member, false);
-
checkAndFixAccess
public static void checkAndFixAccess(Member member, boolean evenIfAlreadyPublic)
Method that is called if aMember
may need forced access, to force a field, method or constructor to be accessible: this is done by callingAccessibleObject.setAccessible(boolean)
.- Parameters:
member
- Accessor to callsetAccessible()
on.evenIfAlreadyPublic
- Whether to always try to make accessor accessible, even ifpublic
(true), or only if needed to force by-pass of non-public
access (false)- Since:
- 2.7
-
isEnumType
public static boolean isEnumType(Class<?> rawType)
Helper method that encapsulates reliable check on whether given raw type "is an Enum", that is, is or extendsEnum
.- Since:
- 2.10.1
-
findEnumType
public static Class<? extends Enum<?>> findEnumType(EnumSet<?> s)
Helper method that can be used to dynamically figure out enumeration type of givenEnumSet
, without having access to its declaration. Code is needed to work around design flaw in JDK.
-
findEnumType
public static Class<? extends Enum<?>> findEnumType(EnumMap<?,?> m)
Helper method that can be used to dynamically figure out enumeration type of givenEnumSet
, without having access to its declaration. Code is needed to work around design flaw in JDK.
-
findEnumType
public static Class<? extends Enum<?>> findEnumType(Enum<?> en)
Helper method that can be used to dynamically figure out formal enumeration type (class) for given enumeration. This is either class of enum instance (for "simple" enumerations), or its superclass (for enums with instance fields or methods)
-
findEnumType
public static Class<? extends Enum<?>> findEnumType(Class<?> cls)
Helper method that can be used to dynamically figure out formal enumeration type (class) for given class of an enumeration value. This is either class of enum instance (for "simple" enumerations), or its superclass (for enums with instance fields or methods)
-
findFirstAnnotatedEnumValue
public static <T extends Annotation> Enum<?> findFirstAnnotatedEnumValue(Class<Enum<?>> enumClass, Class<T> annotationClass)
A method that will look for the first Enum value annotated with the given Annotation.If there's more than one value annotated, the first one found will be returned. Which one exactly is used is undetermined.
- Parameters:
enumClass
- The Enum class to scan for a value with the given annotationannotationClass
- The annotation to look for.- Returns:
- the Enum value annotated with the given Annotation or
null
if none is found. - Throws:
IllegalArgumentException
- if there's a reflection issue accessing the Enum- Since:
- 2.8
-
isJacksonStdImpl
public static boolean isJacksonStdImpl(Object impl)
Method that can be called to determine if given Object is the default implementation Jackson uses; as opposed to a custom serializer installed by a module or calling application. Determination is done usingJacksonStdImpl
annotation on handler (serializer, deserializer etc) class.NOTE: passing `null` is legal, and will result in
true
being returned.
-
isJacksonStdImpl
public static boolean isJacksonStdImpl(Class<?> implClass)
-
isJDKClass
public static boolean isJDKClass(Class<?> rawType)
Accessor for checking whether givenClass
is under Java package ofjava.*
orjavax.*
(including all sub-packages).Added since some aspects of handling need to be changed for JDK types (and possibly some extensions under
javax.
?): for example, forcing of access will not work well for future JDKs (12 and later).Note: in Jackson 2.11 only returned true for
java.*
(and notjavax.*
); was changed in 2.12.- Since:
- 2.11
-
isNonStaticInnerClass
public static boolean isNonStaticInnerClass(Class<?> cls)
-
getPackageName
@Deprecated public static String getPackageName(Class<?> cls)
Deprecated.Since 2.12 (just call methods directly or check class name)- Since:
- 2.7
-
hasEnclosingMethod
public static boolean hasEnclosingMethod(Class<?> cls)
- Since:
- 2.7
-
getDeclaredFields
@Deprecated public static Field[] getDeclaredFields(Class<?> cls)
Deprecated.since 2.11 (just call Class method directly)
-
getDeclaredMethods
@Deprecated public static Method[] getDeclaredMethods(Class<?> cls)
Deprecated.since 2.11 (just call Class method directly)
-
findClassAnnotations
public static Annotation[] findClassAnnotations(Class<?> cls)
- Since:
- 2.7
-
getClassMethods
public static Method[] getClassMethods(Class<?> cls)
Helper method that gets methods declared in given class; usually a simple thing, but sometimes (as per [databind#785]) more complicated, depending on classloader setup.- Since:
- 2.9
-
getConstructors
public static ClassUtil.Ctor[] getConstructors(Class<?> cls)
- Since:
- 2.7
-
-