Java源码示例:com.fasterxml.jackson.databind.util.ClassUtil
示例1
/**
* Method for constructing a {@link CollectionType}.
*<p>
* NOTE: type modifiers are NOT called on Collection type itself; but are called
* for contained types.
*/
public CollectionType constructCollectionType(Class<? extends Collection> collectionClass,
JavaType elementType)
{
TypeBindings bindings = TypeBindings.createIfNeeded(collectionClass, elementType);
CollectionType result = (CollectionType) _fromClass(null, collectionClass, bindings);
// 17-May-2017, tatu: As per [databind#1415], we better verify bound values if (but only if)
// type being resolved was non-generic (i.e.element type was ignored)
if (bindings.isEmpty() && (elementType != null)) {
JavaType t = result.findSuperType(Collection.class);
JavaType realET = t.getContentType();
if (!realET.equals(elementType)) {
throw new IllegalArgumentException(String.format(
"Non-generic Collection class %s did not resolve to something with element type %s but %s ",
ClassUtil.nameOf(collectionClass), elementType, realET));
}
}
return result;
}
示例2
/**
* @since 2.9
*/
protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt,
JavaType bindType)
throws IOException
{
JsonToken t = p.nextToken();
if (t != null) {
Class<?> bt = ClassUtil.rawClass(bindType);
if (bt == null) {
if (_valueToUpdate != null) {
bt = _valueToUpdate.getClass();
}
}
ctxt.reportTrailingTokens(bt, p, t);
}
}
示例3
/**
* Method for constructing a {@link MapType} instance
*<p>
* NOTE: type modifiers are NOT called on constructed type itself; but are called
* for contained types.
*/
public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType) {
TypeBindings bindings = TypeBindings.createIfNeeded(mapClass, new JavaType[] { keyType, valueType });
MapType result = (MapType) _fromClass(null, mapClass, bindings);
// 17-May-2017, tatu: As per [databind#1415], we better verify bound values if (but only if)
// type being resolved was non-generic (i.e.element type was ignored)
if (bindings.isEmpty()) {
JavaType t = result.findSuperType(Map.class);
JavaType realKT = t.getKeyType();
if (!realKT.equals(keyType)) {
throw new IllegalArgumentException(String.format(
"Non-generic Map class %s did not resolve to something with key type %s but %s ",
ClassUtil.nameOf(mapClass), keyType, realKT));
}
JavaType realVT = t.getContentType();
if (!realVT.equals(valueType)) {
throw new IllegalArgumentException(String.format(
"Non-generic Map class %s did not resolve to something with value type %s but %s ",
ClassUtil.nameOf(mapClass), valueType, realVT));
}
}
return result;
}
示例4
protected final JsonDeserializer<Object> _findDefaultImplDeserializer(DeserializationContext ctxt) throws IOException
{
/* 06-Feb-2013, tatu: As per [databind#148], consider default implementation value of
* {@link java.lang.Void} to mean "serialize as null"; as well as DeserializationFeature
* to do swift mapping to null
*/
if (_defaultImpl == null) {
if (!ctxt.isEnabled(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE)) {
return NullifyingDeserializer.instance;
}
return null;
}
Class<?> raw = _defaultImpl.getRawClass();
if (ClassUtil.isBogusClass(raw)) {
return NullifyingDeserializer.instance;
}
synchronized (_defaultImpl) {
if (_defaultImplDeserializer == null) {
_defaultImplDeserializer = ctxt.findContextualValueDeserializer(
_defaultImpl, _property);
}
return _defaultImplDeserializer;
}
}
示例5
/**
* Method that will modify caught exception (passed in as argument)
* as necessary to include reference information, and to ensure it
* is a subtype of {@link IOException}, or an unchecked exception.
*<p>
* Rules for wrapping and unwrapping are bit complicated; essentially:
*<ul>
* <li>Errors are to be passed as is (if uncovered via unwrapping)
* <li>"Plain" IOExceptions (ones that are not of type
* {@link JsonMappingException} are to be passed as is
*</ul>
*/
public void wrapAndThrow(SerializerProvider provider,
Throwable t, Object bean, String fieldName)
throws IOException
{
/* 05-Mar-2009, tatu: But one nasty edge is when we get
* StackOverflow: usually due to infinite loop. But that
* usually gets hidden within an InvocationTargetException...
*/
while (t instanceof InvocationTargetException && t.getCause() != null) {
t = t.getCause();
}
// Errors and "plain" to be passed as is
ClassUtil.throwIfError(t);
// Ditto for IOExceptions... except for mapping exceptions!
boolean wrap = (provider == null) || provider.isEnabled(SerializationFeature.WRAP_EXCEPTIONS);
if (t instanceof IOException) {
if (!wrap || !(t instanceof JsonMappingException)) {
throw (IOException) t;
}
} else if (!wrap) {
ClassUtil.throwIfRTE(t);
}
// Need to add reference information
throw JsonMappingException.wrapWithPath(t, bean, fieldName);
}
示例6
@Override
public void deserializeAndSet(JsonParser p, DeserializationContext ctxt, Object bean)
throws IOException
{
JsonToken t = p.getCurrentToken();
Object value;
if (t == JsonToken.VALUE_NULL) {
value = _valueDeserializer.getNullValue(ctxt);
} else if (_valueTypeDeserializer != null) {
value = _valueDeserializer.deserializeWithType(p, ctxt, _valueTypeDeserializer);
} else { // the usual case
try {
value = _creator.newInstance(bean);
} catch (Exception e) {
ClassUtil.unwrapAndThrowAsIAE(e, String.format(
"Failed to instantiate class %s, problem: %s",
_creator.getDeclaringClass().getName(), e.getMessage()));
value = null;
}
_valueDeserializer.deserialize(p, ctxt, value);
}
set(bean, value);
}
示例7
/**
* Method used by module registration functionality, to construct a new bean
* deserializer factory
* with different configuration settings.
*/
@Override
public DeserializerFactory withConfig(DeserializerFactoryConfig config)
{
if (_factoryConfig == config) {
return this;
}
/* 22-Nov-2010, tatu: Handling of subtypes is tricky if we do immutable-with-copy-ctor;
* and we pretty much have to here either choose between losing subtype instance
* when registering additional deserializers, or losing deserializers.
* Instead, let's actually just throw an error if this method is called when subtype
* has not properly overridden this method; this to indicate problem as soon as possible.
*/
ClassUtil.verifyMustOverride(BeanDeserializerFactory.class, this, "withConfig");
return new BeanDeserializerFactory(config);
}
示例8
/**
* Helper method used when value to serialize is {@link Closeable} and its <code>close()</code>
* method is to be called right after serialization has been called
*/
private final void _writeCloseableValue(JsonGenerator g, Object value, SerializationConfig cfg)
throws IOException
{
Closeable toClose = (Closeable) value;
try {
_serializerProvider(cfg).serializeValue(g, value);
if (cfg.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) {
g.flush();
}
} catch (Exception e) {
ClassUtil.closeOnFailAndThrowAsIOE(null, toClose, e);
return;
}
toClose.close();
}
示例9
@Override public boolean equals(Object o)
{
if (o == this) return true;
if (!ClassUtil.hasClass(o, getClass())) {
return false;
}
TypeBindings other = (TypeBindings) o;
int len = _types.length;
if (len != other.size()) {
return false;
}
JavaType[] otherTypes = other._types;
for (int i = 0; i < len; ++i) {
if (!otherTypes[i].equals(_types[i])) {
return false;
}
}
return true;
}
示例10
protected final AnnotationCollector collectFromBundle(AnnotationCollector c, Annotation bundle) {
Annotation[] anns = ClassUtil.findClassAnnotations(bundle.annotationType());
for (int i = 0, end = anns.length; i < end; ++i) {
Annotation ann = anns[i];
// minor optimization: by-pass 2 common JDK meta-annotations
if (_ignorableAnnotation(ann)) {
continue;
}
if (_intr.isAnnotationBundle(ann)) {
// 11-Apr-2017, tatu: Also must guard against recursive definitions...
if (!c.isPresent(ann)) {
c = c.addOrOverride(ann);
c = collectFromBundle(c, ann);
}
} else {
c = c.addOrOverride(ann);
}
}
return c;
}
示例11
protected final AnnotationCollector collectDefaultFromBundle(AnnotationCollector c, Annotation bundle) {
Annotation[] anns = ClassUtil.findClassAnnotations(bundle.annotationType());
for (int i = 0, end = anns.length; i < end; ++i) {
Annotation ann = anns[i];
// minor optimization: by-pass 2 common JDK meta-annotations
if (_ignorableAnnotation(ann)) {
continue;
}
// also only defaulting, not overrides:
if (!c.isPresent(ann)) {
c = c.addOrOverride(ann);
if (_intr.isAnnotationBundle(ann)) {
c = collectFromBundle(c, ann);
}
}
}
return c;
}
示例12
/**
* Helper method used when value to serialize is {@link Closeable} and its <code>close()</code>
* method is to be called right after serialization has been called
*/
private final void _writeCloseable(JsonGenerator gen, Object value)
throws IOException
{
Closeable toClose = (Closeable) value;
try {
_prefetch.serialize(gen, value, _serializerProvider());
Closeable tmpToClose = toClose;
toClose = null;
tmpToClose.close();
} catch (Exception e) {
ClassUtil.closeOnFailAndThrowAsIOE(gen, toClose, e);
return;
}
gen.close();
}
示例13
/**
* @param ignoreXmlIDREF Whether {@link XmlIDREF} annotation should be processed
* JAXB style (meaning that references are always serialized using id), or
* not (first reference as full POJO, others as ids)
*/
public JaxbAnnotationIntrospector(boolean ignoreXmlIDREF)
{
_ignoreXmlIDREF = ignoreXmlIDREF;
_jaxbPackageName = XmlElement.class.getPackage().getName();
JsonSerializer<?> dataHandlerSerializer = null;
JsonDeserializer<?> dataHandlerDeserializer = null;
// Data handlers included dynamically, to try to prevent issues on platforms
// with less than complete support for JAXB API
try {
dataHandlerSerializer = ClassUtil.createInstance(DataHandlerJsonSerializer.class, false);
dataHandlerDeserializer = ClassUtil.createInstance(DataHandlerJsonDeserializer.class, false);
} catch (Throwable e) {
//dataHandlers not supported...
}
_dataHandlerSerializer = dataHandlerSerializer;
_dataHandlerDeserializer = dataHandlerDeserializer;
}
示例14
protected void _addMethodMixIns(TypeResolutionContext tc, Class<?> targetClass,
Map<MemberKey,MethodBuilder> methods, Class<?> mixInCls)
{
if (_intr == null) {
return;
}
for (Class<?> mixin : ClassUtil.findRawSuperTypes(mixInCls, targetClass, true)) {
for (Method m : ClassUtil.getDeclaredMethods(mixin)) {
if (!_isIncludableMemberMethod(m)) {
continue;
}
final MemberKey key = new MemberKey(m);
MethodBuilder b = methods.get(key);
Annotation[] anns = m.getDeclaredAnnotations();
if (b == null) {
// nothing yet; add but do NOT specify method -- this marks it
// as "mix-over", floating mix-in
methods.put(key, new MethodBuilder(tc, null, collectAnnotations(anns)));
} else {
b.annotations = collectDefaultAnnotations(b.annotations, anns);
}
}
}
}
示例15
private AnnotationCollector _addClassMixIns(AnnotationCollector annotations,
Class<?> target, Class<?> mixin)
{
if (mixin != null) {
// Ok, first: annotations from mix-in class itself:
annotations = _addAnnotationsIfNotPresent(annotations, ClassUtil.findClassAnnotations(mixin));
// And then from its supertypes, if any. But note that we will only consider
// super-types up until reaching the masked class (if found); this because
// often mix-in class is a sub-class (for convenience reasons).
// And if so, we absolutely must NOT include super types of masked class,
// as that would inverse precedence of annotations.
for (Class<?> parent : ClassUtil.findSuperClasses(mixin, target, false)) {
annotations = _addAnnotationsIfNotPresent(annotations, ClassUtil.findClassAnnotations(parent));
}
}
return annotations;
}
示例16
/**
* Helper called to support {@link DeserializationFeature#UNWRAP_SINGLE_VALUE_ARRAYS}:
* default implementation simply calls
* {@link #deserialize(JsonParser, DeserializationContext)},
* but handling may be overridden.
*
* @since 2.9
*/
protected T _deserializeWrappedValue(JsonParser p, DeserializationContext ctxt) throws IOException
{
// 23-Mar-2017, tatu: Let's specifically block recursive resolution to avoid
// either supporting nested arrays, or to cause infinite looping.
if (p.hasToken(JsonToken.START_ARRAY)) {
String msg = String.format(
"Cannot deserialize instance of %s out of %s token: nested Arrays not allowed with %s",
ClassUtil.nameOf(_valueClass), JsonToken.START_ARRAY,
"DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS");
@SuppressWarnings("unchecked")
T result = (T) ctxt.handleUnexpectedToken(_valueClass, p.getCurrentToken(), p, msg);
return result;
}
return (T) deserialize(p, ctxt);
}
示例17
@SuppressWarnings("unchecked")
private XmlAdapter<Object,Object> findAdapterForClass(AnnotatedClass ac, boolean forSerialization)
{
/* As per [JACKSON-411], XmlJavaTypeAdapter should not be inherited from super-class.
* It would still be nice to be able to use mix-ins; but unfortunately we seem to lose
* knowledge of class that actually declared the annotation. Thus, we'll only accept
* declaration from specific class itself.
*/
XmlJavaTypeAdapter adapterInfo = ac.getAnnotated().getAnnotation(XmlJavaTypeAdapter.class);
if (adapterInfo != null) { // should we try caching this?
@SuppressWarnings("rawtypes")
Class<? extends XmlAdapter> cls = adapterInfo.value();
// true -> yes, force access if need be
return ClassUtil.createInstance(cls, true);
}
return null;
}
示例18
/**
* Helper method used to skip processing for types that we know
* cannot be (i.e. are never consider to be) beans:
* things like primitives, Arrays, Enums, and proxy types.
*<p>
* Note that usually we shouldn't really be getting these sort of
* types anyway; but better safe than sorry.
*/
protected boolean isPotentialBeanType(Class<?> type)
{
String typeStr = ClassUtil.canBeABeanType(type);
if (typeStr != null) {
throw new IllegalArgumentException("Cannot deserialize Class "+type.getName()+" (of type "+typeStr+") as a Bean");
}
if (ClassUtil.isProxyType(type)) {
throw new IllegalArgumentException("Cannot deserialize Proxy class "+type.getName()+" as a Bean");
}
/* also: can't deserialize some local classes: static are ok; in-method not;
* other non-static inner classes are ok
*/
typeStr = ClassUtil.isLocalType(type, true);
if (typeStr != null) {
throw new IllegalArgumentException("Cannot deserialize Class "+type.getName()+" (of type "+typeStr+") as a Bean");
}
return true;
}
示例19
/**
* Helper method called by various Map(-like) deserializers.
*/
protected <BOGUS> BOGUS wrapAndThrow(Throwable t, Object ref, String key) throws IOException
{
// to handle StackOverflow:
while (t instanceof InvocationTargetException && t.getCause() != null) {
t = t.getCause();
}
// Errors and "plain" IOExceptions to be passed as is
ClassUtil.throwIfError(t);
// ... except for mapping exceptions
if (t instanceof IOException && !(t instanceof JsonMappingException)) {
throw (IOException) t;
}
// for [databind#1141]
throw JsonMappingException.wrapWithPath(t, ref,
ClassUtil.nonNull(key, "N/A"));
}
示例20
/**
* Helper method called to indicate problem in POJO (serialization) definitions or settings
* regarding specific property (of a type), unrelated to actual JSON content to map.
* Default behavior is to construct and throw a {@link JsonMappingException}.
*
* @since 2.9
*/
public <T> T reportBadPropertyDefinition(BeanDescription bean, BeanPropertyDefinition prop,
String message, Object... msgArgs) throws JsonMappingException {
message = _format(message, msgArgs);
String propName = "N/A";
if (prop != null) {
propName = _quotedString(prop.getName());
}
String beanDesc = "N/A";
if (bean != null) {
beanDesc = ClassUtil.nameOf(bean.getBeanClass());
}
message = String.format("Invalid definition for property %s (of type %s): %s",
propName, beanDesc, message);
throw InvalidDefinitionException.from(getGenerator(), message, bean, prop);
}
示例21
@Override
public Object findInjectableValue(Object valueId, DeserializationContext ctxt,
BeanProperty forProperty, Object beanInstance) throws JsonMappingException
{
if (!(valueId instanceof String)) {
ctxt.reportBadDefinition(ClassUtil.classOf(valueId),
String.format(
"Unrecognized inject value id type (%s), expecting String",
ClassUtil.classNameOf(valueId)));
}
String key = (String) valueId;
Object ob = _values.get(key);
if (ob == null && !_values.containsKey(key)) {
throw new IllegalArgumentException("No injectable id with value '"+key+"' found (for property '"+forProperty.getName()+"')");
}
return ob;
}
示例22
private Throwable throwOrReturnThrowable(Throwable t, DeserializationContext ctxt) throws IOException
{
t = ClassUtil.getRootCause(t);
// Errors to be passed as is
ClassUtil.throwIfError(t);
boolean wrap = (ctxt == null) || ctxt.isEnabled(DeserializationFeature.WRAP_EXCEPTIONS);
// Ditto for IOExceptions; except we may want to wrap JSON exceptions
if (t instanceof IOException) {
if (!wrap || !(t instanceof JsonProcessingException)) {
throw (IOException) t;
}
} else if (!wrap) {
ClassUtil.throwIfRTE(t);
}
return t;
}
示例23
protected <BOGUS> BOGUS _reportWrongToken(JsonParser parser, DeserializationContext context,
JsonToken... expTypes) throws IOException
{
// 20-Apr-2016, tatu: No multiple-expected-types handler yet, construct message here
return context.reportInputMismatch(handledType(),
"Unexpected token (%s), expected one of %s for %s value",
parser.currentToken(),
Arrays.asList(expTypes).toString(),
ClassUtil.getClassDescription(handledType()));
}
示例24
/**
* Method that can be called to obtain an instance of <code>TypeIdResolver</code> of
* specified type.
*/
public TypeResolverBuilder<?> typeResolverBuilderInstance(Annotated annotated,
Class<? extends TypeResolverBuilder<?>> builderClass)
{
HandlerInstantiator hi = getHandlerInstantiator();
if (hi != null) {
TypeResolverBuilder<?> builder = hi.typeResolverBuilderInstance(this, annotated, builderClass);
if (builder != null) {
return builder;
}
}
return (TypeResolverBuilder<?>) ClassUtil.createInstance(builderClass, canOverrideAccessModifiers());
}
示例25
/**
* Method that can be called to obtain an instance of <code>TypeIdResolver</code> of
* specified type.
*/
public TypeIdResolver typeIdResolverInstance(Annotated annotated,
Class<? extends TypeIdResolver> resolverClass)
{
HandlerInstantiator hi = getHandlerInstantiator();
if (hi != null) {
TypeIdResolver builder = hi.typeIdResolverInstance(this, annotated, resolverClass);
if (builder != null) {
return builder;
}
}
return (TypeIdResolver) ClassUtil.createInstance(resolverClass, canOverrideAccessModifiers());
}
示例26
@SuppressWarnings("unchecked")
protected ContainerDeserializerBase(JavaType type, DeserializationConfig config)
{
super(type);
boolean fixAccess = config.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS);
_defaultCtor = (Constructor<T>) ClassUtil.findConstructor(type.getRawClass(), fixAccess);
}
示例27
@Override
public JsonSerializer<Object> serializerInstance(Annotated annotated, Object serDef)
throws JsonMappingException
{
if (serDef == null) {
return null;
}
JsonSerializer<?> ser;
if (serDef instanceof JsonSerializer) {
ser = (JsonSerializer<?>) serDef;
} else {
// Alas, there's no way to force return type of "either class
// X or Y" -- need to throw an exception after the fact
if (!(serDef instanceof Class)) {
reportBadDefinition(annotated.getType(),
"AnnotationIntrospector returned serializer definition of type "
+serDef.getClass().getName()+"; expected type JsonSerializer or Class<JsonSerializer> instead");
}
Class<?> serClass = (Class<?>)serDef;
// there are some known "no class" markers to consider too:
if (serClass == JsonSerializer.None.class || ClassUtil.isBogusClass(serClass)) {
return null;
}
if (!JsonSerializer.class.isAssignableFrom(serClass)) {
reportBadDefinition(annotated.getType(),
"AnnotationIntrospector returned Class "
+serClass.getName()+"; expected Class<JsonSerializer>");
}
HandlerInstantiator hi = _config.getHandlerInstantiator();
ser = (hi == null) ? null : hi.serializerInstance(_config, annotated, serClass);
if (ser == null) {
ser = (JsonSerializer<?>) ClassUtil.createInstance(serClass,
_config.canOverrideAccessModifiers());
}
}
return (JsonSerializer<Object>) _handleResolvable(ser);
}
示例28
@Override
public Object includeFilterInstance(BeanPropertyDefinition forProperty,
Class<?> filterClass)
{
if (filterClass == null) {
return null;
}
HandlerInstantiator hi = _config.getHandlerInstantiator();
Object filter = (hi == null) ? null : hi.includeFilterInstance(_config, forProperty, filterClass);
if (filter == null) {
filter = ClassUtil.createInstance(filterClass,
_config.canOverrideAccessModifiers());
}
return filter;
}
示例29
/**
* Overridable helper method used for special case handling of schema information for
* Enums.
*
* @return True if method handled callbacks; false if not; in latter case caller will
* send default callbacks
*
* @since 2.6
*/
protected boolean _acceptJsonFormatVisitorForEnum(JsonFormatVisitorWrapper visitor,
JavaType typeHint, Class<?> enumType)
throws JsonMappingException
{
// Copied from EnumSerializer#acceptJsonFormatVisitor
JsonStringFormatVisitor stringVisitor = visitor.expectStringFormat(typeHint);
if (stringVisitor != null) {
Set<String> enums = new LinkedHashSet<String>();
for (Object en : enumType.getEnumConstants()) {
try {
// 21-Apr-2016, tatu: This is convoluted to the max, but essentially we
// call `@JsonValue`-annotated accessor method on all Enum members,
// so it all "works out". To some degree.
enums.add(String.valueOf(_accessor.getValue(en)));
} catch (Exception e) {
Throwable t = e;
while (t instanceof InvocationTargetException && t.getCause() != null) {
t = t.getCause();
}
ClassUtil.throwIfError(t);
throw JsonMappingException.wrapWithPath(t, en, _accessor.getName() + "()");
}
}
stringVisitor.enumTypes(enums);
}
return true;
}
示例30
/**
* Method used for creating resolved contextual instances. Must be
* overridden when sub-classing.
*/
protected StdDelegatingSerializer withDelegate(Converter<Object,?> converter,
JavaType delegateType, JsonSerializer<?> delegateSerializer)
{
ClassUtil.verifyMustOverride(StdDelegatingSerializer.class, this, "withDelegate");
return new StdDelegatingSerializer(converter, delegateType, delegateSerializer);
}