Java Code Examples for java.lang.reflect.ParameterizedType#getRawType()

The following examples show how to use java.lang.reflect.ParameterizedType#getRawType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeUtil.java    From blueocean-plugin with MIT License 7 votes vote down vote up
public Type onParameterizdType(ParameterizedType p, Class sup) {
    Class raw = (Class) p.getRawType();
    if(raw==sup) {
        // p is of the form sup<...>
        return p;
    } else {
        // recursively visit super class/interfaces
        Type r = raw.getGenericSuperclass();
        if(r!=null)
            r = visit(bind(r,raw,p),sup);
        if(r!=null)
            return r;
        for( Type i : raw.getGenericInterfaces() ) {
            r = visit(bind(i,raw,p),sup);
            if(r!=null)  return r;
        }
        return null;
    }
}
 
Example 2
Source File: TypeResolver.java    From onetwo with Apache License 2.0 6 votes vote down vote up
/**
 * Populates the {@code map} with with variable/argument pairs for the given {@code types}.
 */
private static void populateSuperTypeArgs(final Type[] types, final Map<TypeVariable<?>, Type> map,
    boolean depthFirst) {
  for (Type type : types) {
    if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;
      if (!depthFirst)
        populateTypeArgs(parameterizedType, map, depthFirst);
      Type rawType = parameterizedType.getRawType();
      if (rawType instanceof Class)
        populateSuperTypeArgs(((Class<?>) rawType).getGenericInterfaces(), map, depthFirst);
      if (depthFirst)
        populateTypeArgs(parameterizedType, map, depthFirst);
    } else if (type instanceof Class) {
      populateSuperTypeArgs(((Class<?>) type).getGenericInterfaces(), map, depthFirst);
    }
  }
}
 
Example 3
Source File: MapperFactory.java    From catatumbo with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link Mapper} for the given class/type.
 * 
 * @param type
 *          the type
 * @return a {@link Mapper} for the given class/type.
 */
private Mapper createMapper(ParameterizedType type) {
  Type rawType = type.getRawType();
  if (!(rawType instanceof Class)) {
    // Don't see how this could ever happen, but just in case...
    throw new IllegalArgumentException(
        String.format("Raw type of ParameterizedType is not a class: %s", type));
  }
  Class<?> rawClass = (Class<?>) rawType;
  Mapper mapper;
  if (Map.class.isAssignableFrom(rawClass)) {
    mapper = new MapMapper(type);
  } else {
    throw new NoSuitableMapperException(String.format("Unsupported type: %s", type));
  }
  return mapper;
}
 
Example 4
Source File: ReflectionNavigator.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public Type onParameterizdType(ParameterizedType p, BinderArg args) {
    Type[] params = p.getActualTypeArguments();

    boolean different = false;
    for (int i = 0; i < params.length; i++) {
        Type t = params[i];
        params[i] = visit(t, args);
        different |= t != params[i];
    }

    Type newOwner = p.getOwnerType();
    if (newOwner != null) {
        newOwner = visit(newOwner, args);
    }
    different |= p.getOwnerType() != newOwner;

    if (!different) {
        return p;
    }

    return new ParameterizedTypeImpl((Class<?>) p.getRawType(), params, newOwner);
}
 
Example 5
Source File: ReflectionUtil.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the full type information from the given type.
 *
 * @param type to be analyzed
 * @return Full type information describing the given type
 */
public static FullTypeInfo getFullTemplateType(Type type) {
	if (type instanceof ParameterizedType) {
		ParameterizedType parameterizedType = (ParameterizedType) type;

		FullTypeInfo[] templateTypeInfos = new FullTypeInfo[parameterizedType.getActualTypeArguments().length];

		for (int i = 0; i < parameterizedType.getActualTypeArguments().length; i++) {
			templateTypeInfos[i] = getFullTemplateType(parameterizedType.getActualTypeArguments()[i]);
		}

		return new FullTypeInfo((Class<?>) parameterizedType.getRawType(), templateTypeInfos);
	} else {
		return new FullTypeInfo((Class<?>) type, null);
	}
}
 
Example 6
Source File: Utils.java    From KakaCache-RxJava with GNU General Public License v3.0 5 votes vote down vote up
public static Class<?> getRawType(Type type) {
    if (type == null) throw new NullPointerException("type == null");

    if (type instanceof Class<?>) {
        // Type is a normal class.
        return (Class<?>) type;
    }
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;

        // I'm not exactly sure why getRawType() returns Type instead of Class. Neal isn't either but
        // suspects some pathological case related to nested classes exists.
        Type rawType = parameterizedType.getRawType();
        if (!(rawType instanceof Class)) throw new IllegalArgumentException();
        return (Class<?>) rawType;
    }
    if (type instanceof GenericArrayType) {
        Type componentType = ((GenericArrayType) type).getGenericComponentType();
        return Array.newInstance(getRawType(componentType), 0).getClass();
    }
    if (type instanceof TypeVariable) {
        // We could use the variable's bounds, but that won't work if there are multiple. Having a raw
        // type that's more general than necessary is okay.
        return Object.class;
    }
    if (type instanceof WildcardType) {
        return getRawType(((WildcardType) type).getUpperBounds()[0]);
    }

    throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
            + "GenericArrayType, but <" + type + "> is of type " + type.getClass().getName());
}
 
Example 7
Source File: AbstractClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected static Class<?> getCallbackClass(Type outType) {
    Class<?> respClass = null;
    if (outType instanceof Class) {
        respClass = (Class<?>)outType;
    } else if (outType instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType)outType;
        if (pt.getRawType() instanceof Class) {
            respClass = (Class<?>)pt.getRawType();
        }
    } else if (outType == null) {
        respClass = Response.class;
    }
    return respClass;
}
 
Example 8
Source File: TypeRegistry.java    From glitr with MIT License 5 votes vote down vote up
private GraphQLType getGraphQLTypeForOutputParameterizedType(Type type, String name, boolean fromInterface) {
    ParameterizedType parameterizedType = (ParameterizedType) type;
    Type containerType = parameterizedType.getRawType();

    if (Collection.class.isAssignableFrom((Class)containerType)) {
        return createListOutputTypeFromParametrizedType(type, fromInterface);
    } else if (containerType == rx.Observable.class) {
        Type[] fieldArgTypes = parameterizedType.getActualTypeArguments();
        return convertToGraphQLOutputType(fieldArgTypes[0], name, fromInterface);
    } else {
        throw new IllegalArgumentException("Unable to convert type " + type.getTypeName() + " to GraphQLOutputType");
    }
}
 
Example 9
Source File: TypeUtils.java    From dolphin-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Format a {@link ParameterizedType} as a {@link String}.
 *
 * @param p {@code ParameterizedType} to format
 * @return String
 * @since 3.2
 */
private static String parameterizedTypeToString(final ParameterizedType p) {
    final StringBuilder buf = new StringBuilder();

    final Type useOwner = p.getOwnerType();
    final Class<?> raw = (Class<?>) p.getRawType();

    if (useOwner == null) {
        buf.append(raw.getName());
    } else {
        if (useOwner instanceof Class<?>) {
            buf.append(((Class<?>) useOwner).getName());
        } else {
            buf.append(useOwner.toString());
        }
        buf.append('.').append(raw.getSimpleName());
    }

    final int[] recursiveTypeIndexes = findRecursiveTypes(p);

    if (recursiveTypeIndexes.length > 0) {
        appendRecursiveTypes(buf, recursiveTypeIndexes, p.getActualTypeArguments());
    } else {
        appendAllTo(buf.append('<'), ", ", p.getActualTypeArguments()).append('>');
    }

    return buf.toString();
}
 
Example 10
Source File: $Gson$Types.java    From gson with Apache License 2.0 5 votes vote down vote up
public static Class<?> getRawType(Type type) {
  if (type instanceof Class<?>) {
    // type is a normal class.
    return (Class<?>) type;

  } else if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType = (ParameterizedType) type;

    // I'm not exactly sure why getRawType() returns Type instead of Class.
    // Neal isn't either but suspects some pathological case related
    // to nested classes exists.
    Type rawType = parameterizedType.getRawType();
    checkArgument(rawType instanceof Class);
    return (Class<?>) rawType;

  } else if (type instanceof GenericArrayType) {
    Type componentType = ((GenericArrayType)type).getGenericComponentType();
    return Array.newInstance(getRawType(componentType), 0).getClass();

  } else if (type instanceof TypeVariable) {
    // we could use the variable's bounds, but that won't work if there are multiple.
    // having a raw type that's more general than necessary is okay
    return Object.class;

  } else if (type instanceof WildcardType) {
    return getRawType(((WildcardType) type).getUpperBounds()[0]);

  } else {
    String className = type == null ? "null" : type.getClass().getName();
    throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
        + "GenericArrayType, but <" + type + "> is of type " + className);
  }
}
 
Example 11
Source File: ReflectionUtils.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
public static boolean isListOfListOfObject(Type type) {
	if(type instanceof ParameterizedType) {
		ParameterizedType secondGenericType = (ParameterizedType) type;
		Class<?> rowType = (Class<?>) secondGenericType.getRawType();
		if(!List.class.isAssignableFrom(rowType)) {
			return false;
		}
		Class<?> genericObject = (Class<?>) secondGenericType.getActualTypeArguments()[0];

		if(genericObject.equals(Object.class)) {
			return true;
		}
	}
	return false;
}
 
Example 12
Source File: JsonResponseUtils.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
private static String getTypeName(Type type) {

    if (type instanceof Class) {

      Class<?> clazz = (Class<?>) type;
      return clazz.getSimpleName();

    } else if (type instanceof ParameterizedType) {

      StringBuilder sb = new StringBuilder();

      ParameterizedType paramType = (ParameterizedType) type;
      Class<?> rawClass = (Class<?>) paramType.getRawType();

      sb.append(rawClass.getSimpleName());

      Type[] arguments = paramType.getActualTypeArguments();
      if (arguments.length > 0) {
        sb.append('<');
        for (Type argType : arguments) {
          sb.append(getTypeName(argType));
          sb.append(',');
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append('>');
      }

      return sb.toString();
    }

    return type.toString();
  }
 
Example 13
Source File: InjectionUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Class<?> getRawType(Type genericType) {

        if (genericType instanceof Class) {
            return (Class<?>) genericType;
        } else if (genericType instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType)genericType;
            Type t = paramType.getRawType();
            if (t instanceof Class) {
                return (Class<?>)t;
            }
        } else if (genericType instanceof GenericArrayType) {
            return getRawType(((GenericArrayType)genericType).getGenericComponentType());
        }
        return null;
    }
 
Example 14
Source File: MetaPartitionBase.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private Optional<MetaElement> allocateMap(ParameterizedType paramType) {
	if (paramType.getRawType() instanceof Class && Map.class.isAssignableFrom((Class<?>) paramType.getRawType())) {
		PreconditionUtil.assertEquals("expected 2 type arguments", 2, paramType.getActualTypeArguments().length);

		Optional<MetaType> optKeyType = (Optional) allocateMetaElement(paramType.getActualTypeArguments()[0]);
		Optional<MetaType> optValueType = (Optional) allocateMetaElement(paramType.getActualTypeArguments()[1]);
		if (optKeyType.isPresent() && optValueType.isPresent()) {
			MetaType keyType = optKeyType.get();
			MetaType valueType = optValueType.get();
			MetaMapType mapMeta = new MetaMapType();

			boolean primitiveKey = keyType instanceof MetaPrimitiveType;
			boolean primitiveValue = valueType instanceof MetaPrimitiveType;
			if (primitiveKey || !primitiveValue) {
				mapMeta.setName(valueType.getName() + "$mappedBy$" + keyType.getName());
				mapMeta.setId(valueType.getId() + "$mappedBy$" + keyType.getName());
			} else {
				mapMeta.setName(keyType.getName() + "$map$" + valueType.getName());
				mapMeta.setId(keyType.getId() + "$map$" + valueType.getName());
			}

			mapMeta.setImplementationType(paramType);
			mapMeta.setKeyType(keyType);
			mapMeta.setElementType(valueType);
			return addElement(paramType, mapMeta);
		}
	}
	return Optional.empty();
}
 
Example 15
Source File: TypeResolver.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
private static void fill ( final Map<TypeVariable<?>, Type> result, final Type genericClass )
{
    if ( genericClass instanceof Class<?> )
    {
        fillFrom ( (Class<?>)genericClass, result );
    }
    else if ( genericClass instanceof ParameterizedType )
    {
        final ParameterizedType pt = (ParameterizedType)genericClass;
        final Type rt = pt.getRawType ();

        if ( rt instanceof Class<?> )
        {
            final Class<?> rtc = (Class<?>)rt;

            final TypeVariable<?>[] tp = rtc.getTypeParameters ();
            final Type[] atp = pt.getActualTypeArguments ();

            for ( int i = 0; i < tp.length; i++ )
            {
                Type at = atp[i];
                if ( at instanceof TypeVariable<?> )
                {
                    at = result.get ( at );
                }
                result.put ( tp[i], at );
            }

            fillFrom ( rtc, result );
        }
    }
}
 
Example 16
Source File: TypeReference.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * @since 1.2.9
 * @param actualTypeArguments
 */
protected TypeReference(Type... actualTypeArguments){
    Class<?> thisClass = this.getClass();
    Type superClass = thisClass.getGenericSuperclass();

    ParameterizedType argType = (ParameterizedType) ((ParameterizedType) superClass).getActualTypeArguments()[0];
    Type rawType = argType.getRawType();
    Type[] argTypes = argType.getActualTypeArguments();

    int actualIndex = 0;
    for (int i = 0; i < argTypes.length; ++i) {
        if (argTypes[i] instanceof TypeVariable &&
                actualIndex < actualTypeArguments.length) {
            argTypes[i] = actualTypeArguments[actualIndex++];
        }
        // fix for openjdk and android env
        if (argTypes[i] instanceof GenericArrayType) {
            argTypes[i] = TypeUtils.checkPrimitiveArray(
                    (GenericArrayType) argTypes[i]);
        }

        // 如果有多层泛型且该泛型已经注明实现的情况下,判断该泛型下一层是否还有泛型
        if(argTypes[i] instanceof ParameterizedType) {
            argTypes[i] = handlerParameterizedType((ParameterizedType) argTypes[i], actualTypeArguments, actualIndex);
        }
    }

    Type key = new ParameterizedTypeImpl(argTypes, thisClass, rawType);
    Type cachedType = classTypeCache.get(key);
    if (cachedType == null) {
        classTypeCache.putIfAbsent(key, key);
        cachedType = classTypeCache.get(key);
    }

    type = cachedType;

}
 
Example 17
Source File: MoreTypes.java    From soabase-halva with Apache License 2.0 5 votes vote down vote up
public static Class<?> getRawType(Type type) {
  if (type instanceof Class<?>) {
    // type is a normal class.
    return (Class<?>) type;

  } else if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType = (ParameterizedType) type;

    // I'm not exactly sure why getRawType() returns Type instead of Class.
    // Neal isn't either but suspects some pathological case related
    // to nested classes exists.
    Type rawType = parameterizedType.getRawType();
    checkArgument(rawType instanceof Class,
        "Expected a Class, but <%s> is of type %s", type, type.getClass().getName());
    return (Class<?>) rawType;

  } else if (type instanceof GenericArrayType) {
    Type componentType = ((GenericArrayType)type).getGenericComponentType();
    return Array.newInstance(getRawType(componentType), 0).getClass();

  } else if (type instanceof TypeVariable) {
    // we could use the variable's bounds, but that'll won't work if there are multiple.
    // having a raw type that's more general than necessary is okay  
    return Object.class;

  } else {
    throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
        + "GenericArrayType, but <" + type + "> is of type " + type.getClass().getName());
  }
}
 
Example 18
Source File: ParameterizedTypeImpl.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (o instanceof ParameterizedType) {
        // Check that information is equivalent
        ParameterizedType that = (ParameterizedType) o;

        if (this == that)
            return true;

        Type thatOwner   = that.getOwnerType();
        Type thatRawType = that.getRawType();

        if (false) { // Debugging
            boolean ownerEquality = (ownerType == null ?
                                     thatOwner == null :
                                     ownerType.equals(thatOwner));
            boolean rawEquality = (rawType == null ?
                                   thatRawType == null :
                                   rawType.equals(thatRawType));

            boolean typeArgEquality = Arrays.equals(actualTypeArguments, // avoid clone
                                                    that.getActualTypeArguments());
            for (Type t : actualTypeArguments) {
                System.out.printf("\t\t%s%s%n", t, t.getClass());
            }

            System.out.printf("\towner %s\traw %s\ttypeArg %s%n",
                              ownerEquality, rawEquality, typeArgEquality);
            return ownerEquality && rawEquality && typeArgEquality;
        }


        return
            (ownerType == null ?
             thatOwner == null :
             ownerType.equals(thatOwner)) &&
            (rawType == null ?
             thatRawType == null :
             rawType.equals(thatRawType)) &&
            Arrays.equals(actualTypeArguments, // avoid clone
                          that.getActualTypeArguments());
    } else
        return false;
}
 
Example 19
Source File: MapCodec.java    From Simplify-Core with Apache License 2.0 4 votes vote down vote up
private Map<Object, Object> createMap(Type type) {
    // TODO: 2017/7/5  Properties key可能不为String,要增加这个Properties类型的测试用例
    if (type == Properties.class) {
        return new Properties();
    }

    if (type == Hashtable.class) {
        return new Hashtable();
    }

    if (type == IdentityHashMap.class) {
        return new IdentityHashMap();
    }

    if (type == SortedMap.class || type == TreeMap.class) {
        return new TreeMap();
    }

    if (type == ConcurrentMap.class || type == ConcurrentHashMap.class) {
        return new ConcurrentHashMap();
    }

    if (type == Map.class || type == HashMap.class) {
        return new HashMap();
    }

    if (type == LinkedHashMap.class) {
        return new LinkedHashMap();
    }

    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;

        Type rawType = parameterizedType.getRawType();
        if (EnumMap.class.equals(rawType)) {
            Type[] actualArgs = parameterizedType.getActualTypeArguments();
            return new EnumMap((Class) actualArgs[0]);
        }

        return createMap(rawType);
    }

    Class<?> clazz = (Class<?>) type;
    if (clazz.isInterface()) {
        throw new JsonException("unsupport type " + type);
    }

    try {
        return (Map<Object, Object>) clazz.newInstance();
    } catch (Exception e) {
        throw new JsonException("unsupport type " + type, e);
    }
}
 
Example 20
Source File: EntityToVoMapper.java    From mPaaS with Apache License 2.0 4 votes vote down vote up
/** 拷贝固定属性 */
private void copyFixedProperty(MapperContext context, Object srcValue)
		throws Exception {
	// 源可读,目标可写
	Method write = context.targetDesc.getWriteMethod();
	if (!accessable(write)) {
		return;
	}
	// 转换目标值
	Object value;
	Type targetType = write.getGenericParameterTypes()[0];
	if (targetType instanceof ParameterizedType) {
		// 泛型,仅支持数组
		ParameterizedType pType = (ParameterizedType) targetType;
		Class<?> rawType = (Class<?>) pType.getRawType();
		if (Collection.class.isAssignableFrom(rawType)) {
			Type elemType = pType.getActualTypeArguments()[0];
			// 读取元素类型
			Class<?> elemClass = null;
			if (elemType instanceof Class) {
				elemClass = (Class<?>) elemType;
			} else if (elemType instanceof TypeVariable) {
				elemClass = ReflectUtil.getActualClass(
						context.target.getClass(),
						write.getDeclaringClass(),
						((TypeVariable<?>) elemType).getName());
			}
			if (elemClass == null) {
				throw new Exception("未识别的数组元素类型");
			}
			value = castListValue(context, (Collection<?>) srcValue,
					elemClass);
		} else {
			throw new Exception("泛型仅支持Collection");
		}
	} else {
		// 非泛型,读取目标类型
		Class<?> targetClass = null;
		if (targetType instanceof Class) {
			targetClass = (Class<?>) targetType;
		} else if (targetType instanceof TypeVariable) {
			targetClass = ReflectUtil.getActualClass(
					context.target.getClass(),
					write.getDeclaringClass(),
					((TypeVariable<?>) targetType).getName());
		}
		if (targetClass == null) {
			throw new Exception("未知的字段类型");
		}
		value = castSingleValue(context, srcValue, targetClass);
	}
	// 写值
	write.invoke(context.target, new Object[] { value });
}