下面列出了com.fasterxml.jackson.databind.JavaType#getRawClass ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public boolean useForType(JavaType type) {
Class<?> clazz = type.getRawClass();
// Note: This does not work well with generics defined at or above the same scope as the call
// to marshal or unmarshal. As a result, only use such generics there when dealing with a primitive
// type or registered class, as these will cope with the idResolver.
// We can lookup the class in the registry, for marshalling and unmarshalling.
Boolean registryHasClass = registry.isClass(clazz);
// We only ever declare as object if we intend to use one of our own classes (or a primitive).
Boolean isObject = (Object.class.equals(clazz));
// Also include abstract classes and interfaces as these are always defined with a type id. This
// is not the case for container types, however, so these are excluded.
Boolean isAbstract = type.isAbstract();
Boolean isInterface = type.isInterface();
Boolean isNotContainer = !type.isContainerType();
// Primitive types are considered abstract, so exclude these as well.
Boolean isNotPrimitive = !type.isPrimitive();
return registryHasClass || ((isObject || isAbstract || isInterface) && isNotContainer && isNotPrimitive);
}
/**
* Method similar to {@link #constructSpecializedType}, but that creates a
* less-specific type of given type. Usually this is as simple as simply
* finding super-type with type erasure of <code>superClass</code>, but
* there may be need for some additional work-arounds.
*
* @param superClass
*
* @since 2.7
*/
public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass)
{
// simple optimization to avoid costly introspection if type-erased type does NOT differ
final Class<?> rawBase = baseType.getRawClass();
if (rawBase == superClass) {
return baseType;
}
JavaType superType = baseType.findSuperType(superClass);
if (superType == null) {
// Most likely, caller did not verify sub/super-type relationship
if (!superClass.isAssignableFrom(rawBase)) {
throw new IllegalArgumentException(String.format(
"Class %s not a super-type of %s", superClass.getName(), baseType));
}
// 01-Nov-2015, tatu: Should never happen, but ch
throw new IllegalArgumentException(String.format(
"Internal error: class %s not included as super-type for %s",
superClass.getName(), baseType));
}
return superType;
}
public static Type java2Type(JavaType java) {
Type type = null;
if (java.isArrayType()) {
// 数组类型
type = java.getRawClass();
} else if (java.hasGenericTypes()) {
// 泛型类型
List<JavaType> javas = java.getBindings().getTypeParameters();
Type[] generics = new Type[javas.size()];
int index = 0;
for (JavaType term : javas) {
generics[index++] = java2Type(term);
}
Class<?> clazz = java.getRawClass();
type = TypeUtility.parameterize(clazz, generics);
} else {
type = java.getRawClass();
}
return type;
}
@Override
public JavaType modifyType(JavaType type, Type jdkType, TypeBindings bindings, TypeFactory typeFactory)
{
if (type.isReferenceType() || type.isContainerType()) {
return type;
}
final Class<?> raw = type.getRawClass();
// First: make Multimaps look more Map-like
if (raw == Multimap.class) {
return MapLikeType.upgradeFrom(type,
type.containedTypeOrUnknown(0),
type.containedTypeOrUnknown(1));
}
if (raw == Optional.class) {
return ReferenceType.upgradeFrom(type, type.containedTypeOrUnknown(0));
}
return type;
}
@Override
public JsonSerializer<Object> createSerializer(SerializerProvider prov, JavaType type) throws JsonMappingException {
if (type.getRawClass() == TestBeanSimple.class) {
return new TestBeanSimpleSerializer();
}
else {
return super.createSerializer(prov, type);
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Check that it's a JSON-RPC method
MethodMetadata methodMetadata = classMetadata.getMethods().get(method);
if (methodMetadata == null) {
throw new IllegalStateException("Method '" + method.getName() + "' is not JSON-RPC available");
}
// Get method name (annotation or the actual name), params and id generator
String methodName = methodMetadata.getName();
JsonNode params = getParams(methodMetadata, args, getParamsType(classMetadata, methodMetadata));
IdGenerator<?> idGenerator = userIdGenerator != null ? userIdGenerator : classMetadata.getIdGenerator();
// Construct a request
ValueNode id = new POJONode(idGenerator.generate());
String textResponse = execute(request(id, methodName, params));
// Parse a response
JsonNode responseNode = mapper.readTree(textResponse);
JsonNode result = responseNode.get(RESULT);
JsonNode error = responseNode.get(ERROR);
if (result != null) {
JavaType returnType = mapper.getTypeFactory().constructType(method.getGenericReturnType());
if (returnType.getRawClass() == void.class) {
return null;
}
return mapper.convertValue(result, returnType);
} else {
ErrorMessage errorMessage = mapper.treeToValue(error, ErrorMessage.class);
throw new JsonRpcException(errorMessage);
}
}
/**
* NOTE: should not be called for generic types.
*/
public Class<?> materializeRawType(MapperConfig<?> config, AnnotatedClass typeDef)
{
final JavaType type = typeDef.getType();
Class<?> rawType = type.getRawClass();
String newName = _defaultPackage+rawType.getName();
BeanBuilder builder = BeanBuilder.construct(config, type, typeDef);
byte[] bytecode = builder.implement(isEnabled(Feature.FAIL_ON_UNMATERIALIZED_METHOD)).build(newName);
return _classLoader.loadAndResolve(newName, bytecode, rawType);
}
AnnotatedClassResolver(MapperConfig<?> config, JavaType type, MixInResolver r) {
_config = config;
_type = type;
_class = type.getRawClass();
_mixInResolver = r;
_bindings = type.getBindings();
_intr = config.isAnnotationProcessingEnabled()
? config.getAnnotationIntrospector() : null;
_primaryMixin = _config.findMixInClassFor(_class);
}
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
if (type.isSchemaProperty()) {
JavaType javaType = Json.mapper().constructType(type.getType());
Class<?> cls = javaType.getRawClass();
if (AbstractRequestBuilder.isRequestTypeToIgnore(cls))
return null;
}
return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
}
protected boolean _suitableType(JavaType type)
{
// Future plans may include calling of this method for all kinds of abstract types.
// So as simple precaution, let's limit kinds of types we will try materialize
// implementations for.
if (type.isContainerType() || type.isReferenceType()
|| type.isEnumType() || type.isPrimitive()) {
return false;
}
Class<?> cls = type.getRawClass();
if ((cls == Number.class)
// 22-Jun-2016, tatu: As per [#12], avoid these too
|| (cls == Date.class) || (cls == Calendar.class)
|| (cls == CharSequence.class) || (cls == Iterable.class) || (cls == Iterator.class)
// 06-Feb-2019, tatu: [modules-base#74] and:
|| (cls == java.io.Serializable.class)
) {
return false;
}
// Fail on non-public classes, since we can't easily force access to such
// classes (unless we tried to generate impl classes in same package)
if (!Modifier.isPublic(cls.getModifiers())) {
if (isEnabled(Feature.FAIL_ON_NON_PUBLIC_TYPES)) {
throw new IllegalArgumentException("Can not materialize implementation of "+cls+" since it is not public ");
}
return false;
}
return true;
}
@SuppressWarnings("unchecked")
public MessageWriteSchema(ProtoMapper protoMapper, Message message, JavaType javaType) {
this.protoMapper = protoMapper;
this.message = message;
this.javaType = javaType;
this.mainPojoCls = (Class<T>) javaType.getRawClass();
}
@Override
public JavaType modifyType(JavaType type, Type jdkType, TypeBindings bindings, TypeFactory typeFactory)
{
final Class<?> raw = type.getRawClass();
if (Seq.class.isAssignableFrom(raw) && CharSeq.class != raw) {
return CollectionLikeType.upgradeFrom(type, type.containedTypeOrUnknown(0));
}
if (Set.class.isAssignableFrom(raw)) {
return CollectionLikeType.upgradeFrom(type, type.containedTypeOrUnknown(0));
}
if (PriorityQueue.class.isAssignableFrom(raw)) {
return CollectionLikeType.upgradeFrom(type, type.containedTypeOrUnknown(0));
}
if (Map.class.isAssignableFrom(raw)) {
return MapLikeType.upgradeFrom(type, type.containedTypeOrUnknown(0), type.containedTypeOrUnknown(1));
}
if (Multimap.class.isAssignableFrom(raw)) {
return MapLikeType.upgradeFrom(type, type.containedTypeOrUnknown(0), type.containedTypeOrUnknown(1));
}
if (Lazy.class.isAssignableFrom(raw)) {
return ReferenceType.upgradeFrom(type, type.containedTypeOrUnknown(0));
}
if (Option.class.isAssignableFrom(raw)) {
return ReferenceType.upgradeFrom(type, type.containedTypeOrUnknown(0));
}
return type;
}
@Override
public JsonSerializer<Object> createSerializer(SerializerProvider prov, JavaType type) throws JsonMappingException {
if (type.getRawClass() == TestBeanSimple.class) {
return new TestBeanSimpleSerializer();
}
else {
return super.createSerializer(prov, type);
}
}
@Override
@Nullable
public JsonDeserializer<?> findBeanDeserializer(
JavaType type, DeserializationConfig config, BeanDescription beanDesc) {
if (Message.class.isAssignableFrom(type.getRawClass())) {
return new MessageDeserializer(type.getRawClass());
}
return null;
}
private Map<String,FieldBuilder> _findFields(TypeResolutionContext tc,
JavaType type, Map<String,FieldBuilder> fields)
{
// First, a quick test: we only care for regular classes (not interfaces,
//primitive types etc), except for Object.class. A simple check to rule out
// other cases is to see if there is a super class or not.
JavaType parent = type.getSuperClass();
if (parent == null) {
return fields;
}
final Class<?> cls = type.getRawClass();
// Let's add super-class' fields first, then ours.
fields = _findFields(new TypeResolutionContext.Basic(_typeFactory, parent.getBindings()),
parent, fields);
for (Field f : ClassUtil.getDeclaredFields(cls)) {
// static fields not included (transients are at this point, filtered out later)
if (!_isIncludableField(f)) {
continue;
}
// Ok now: we can (and need) not filter out ignorable fields at this point; partly
// because mix-ins haven't been added, and partly because logic can be done
// when determining get/settability of the field.
if (fields == null) {
fields = new LinkedHashMap<>();
}
FieldBuilder b = new FieldBuilder(tc, f);
if (_intr != null) {
b.annotations = collectAnnotations(b.annotations, f.getDeclaredAnnotations());
}
fields.put(f.getName(), b);
}
// And then... any mix-in overrides?
if (_mixInResolver != null) {
Class<?> mixin = _mixInResolver.findMixInClassFor(cls);
if (mixin != null) {
_addFieldMixIns(mixin, cls, fields);
}
}
return fields;
}
public Referring(UnresolvedForwardReference ref, JavaType beanType) {
_reference = ref;
_beanType = beanType.getRawClass();
}
@Override
public JsonSerializer<?> findSerializer(SerializationConfig config, JavaType type, BeanDescription beanDesc) {
if (Tuple1.class==type.getRawClass()) {
return new Tuple1Serializer();
}
if (Tuple2.class==type.getRawClass()) {
return new Tuple2Serializer();
}
if (Tuple3.class==type.getRawClass()) {
return new Tuple3Serializer();
}
if (Tuple4.class==type.getRawClass()) {
return new Tuple4Serializer();
}
if (Tuple5.class==type.getRawClass()) {
return new Tuple5Serializer();
}
if (Tuple6.class==type.getRawClass()) {
return new Tuple6Serializer();
}
if (Tuple7.class==type.getRawClass()) {
return new Tuple7Serializer();
}
if (Tuple8.class==type.getRawClass()) {
return new Tuple8Serializer();
}
if(PersistentMap.class.isAssignableFrom(type.getRawClass())) {
return new PersistentMapSerializer();
}
if (Either.class.isAssignableFrom(type.getRawClass())) {
return new Sealed2Serializer();
}
if (Sealed2.class.isAssignableFrom(type.getRawClass())) {
return new Sealed2Serializer();
}
if (Sealed3.class.isAssignableFrom(type.getRawClass())) {
return new Sealed3Serializer();
}
if (Sealed4.class.isAssignableFrom(type.getRawClass())) {
return new Sealed4Serializer();
}
if (Sealed5.class.isAssignableFrom(type.getRawClass())) {
return new Sealed5Serializer();
}
return super.findSerializer(config, type, beanDesc);
}
public void validateSubType(DeserializationContext ctxt, JavaType type,
BeanDescription beanDesc) throws JsonMappingException
{
// There are certain nasty classes that could cause problems, mostly
// via default typing -- catch them here.
final Class<?> raw = type.getRawClass();
String full = raw.getName();
main_check:
do {
if (_cfgIllegalClassNames.contains(full)) {
break;
}
// 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling
// for some Spring framework types
// 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces
if (raw.isInterface()) {
;
} else if (full.startsWith(PREFIX_SPRING)) {
for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()){
String name = cls.getSimpleName();
// looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there?
if ("AbstractPointcutAdvisor".equals(name)
// ditto for "FileSystemXmlApplicationContext": block all ApplicationContexts
|| "AbstractApplicationContext".equals(name)) {
break main_check;
}
}
} else if (full.startsWith(PREFIX_C3P0)) {
// [databind#1737]; more 3rd party
// s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource");
// s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource");
// [databind#1931]; more 3rd party
// com.mchange.v2.c3p0.ComboPooledDataSource
// com.mchange.v2.c3p0.debug.AfterCloseLoggingComboPooledDataSource
if (full.endsWith("DataSource")) {
break main_check;
}
}
return;
} while (false);
ctxt.reportBadTypeDefinition(beanDesc,
"Illegal type (%s) to deserialize: prevented for security reasons", full);
}
@Override
public Schema resolve(AnnotatedType annotatedType, ModelConverterContext context, Iterator<ModelConverter> next)
{
JavaType classType = TypeFactory.defaultInstance().constructType(annotatedType.getType());
Class<?> rawClass = classType.getRawClass();
JavaType resolvedType = classType;
if ((rawClass != null) &&!resolvedType.isPrimitive())
{
if (rawClass.isAssignableFrom(ServerResponse.class))
{
resolvedType = classType.containedType(0);
}
else if (rawClass.isAssignableFrom(CompletableFuture.class))
{
Class<?> futureCls = classType.containedType(0).getRawClass();
if (futureCls.isAssignableFrom(ServerResponse.class))
{
final JavaType futureType = TypeFactory.defaultInstance().constructType(classType.containedType(0));
resolvedType = futureType.containedType(0);
}
else
{
resolvedType = classType.containedType(0);
}
}
if (resolvedType != null)
{
if (resolvedType.getTypeName().contains("java.lang.Void"))
{
resolvedType = TypeFactory.defaultInstance().constructFromCanonical(Void.class.getName());
}
else if (resolvedType.getTypeName().contains("Optional"))
{
if (resolvedType.getTypeName().contains("java.nio.file.Path"))
{
resolvedType = TypeFactory.defaultInstance().constructParametricType(Optional.class, File.class);
}
if (resolvedType.getTypeName().contains("ByteBuffer"))
{
resolvedType = TypeFactory.defaultInstance().constructParametricType(Optional.class, File.class);
}
}
else
{
if (resolvedType.getTypeName().contains("java.nio.file.Path"))
{
resolvedType = TypeFactory.defaultInstance().constructFromCanonical(File.class.getName());
}
if (resolvedType.getTypeName().contains("ByteBuffer"))
{
resolvedType = TypeFactory.defaultInstance().constructFromCanonical(File.class.getName());
}
}
annotatedType.setType(resolvedType);
}
}
try {
return super.resolve(annotatedType, context, next);
} catch (Exception e) {
log.error("Error processing " + annotatedType + " " + classType + " " + annotatedType.getName(), e);
return null;
}
}
/**
* Is concrete class boolean.
*
* @param type the type
* @return the boolean
*/
private boolean isConcreteClass(AnnotatedType type) {
JavaType javaType = Json.mapper().constructType(type.getType());
Class<?> clazz = javaType.getRawClass();
return !Modifier.isAbstract(clazz.getModifiers()) && !clazz.isInterface();
}