本文整理汇总了Java中org.apache.commons.lang3.reflect.TypeUtils.isAssignable方法的典型用法代码示例。如果您正苦于以下问题:Java TypeUtils.isAssignable方法的具体用法?Java TypeUtils.isAssignable怎么用?Java TypeUtils.isAssignable使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.commons.lang3.reflect.TypeUtils
的用法示例。
在下文中一共展示了TypeUtils.isAssignable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getCollectionType
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
/**
* Return the type of the content of the given collection type.
*
* @param type The collection type.
* @return Collection type.
*/
public static Class<?> getCollectionType(Type type) {
if (TypeUtils.isAssignable(type, Collection.class)) {
if (type instanceof ParameterizedType) {
Type genericType = ((ParameterizedType) type).getActualTypeArguments()[0];
if (genericType instanceof Class) {
return (Class<?>) genericType;
}
} else {
throw new IllegalArgumentException("Cannot infer index type for non-parameterized type: " + type);
}
} else if (TypeUtils.isArrayType(type)) {
return (Class<?>) TypeUtils.getArrayComponentType(type);
}
throw new IllegalArgumentException("Unsupported type: " + type);
}
示例2: generateIdIfAbsentFromDocument
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
@Override
public T generateIdIfAbsentFromDocument(T document) {
if (idGenerator != null && !documentHasId(document)) {
Object generatedId = idGenerator.generate();
try {
if (!idField.setFieldValue(document, generatedId)) {
LOGGER.error("Id {} for pojo {} could not be set. Please watch the logs.", generatedId, document);
throw new IdGenerationException("Id could not be generated for pojo. See logs for details.");
}
} catch (TypeMismatchException e) {
if (generatedId != null && !TypeUtils.isAssignable(generatedId.getClass(), idField.fieldTypePair.realType)) {
LOGGER.error("Your set id generator {} for the id field {} produces non-assignable values.", idGenerator, idField, e);
}
else {
LOGGER.error("Some unspecified error occurred while generating an id {} for your pojo {}", generatedId, document);
}
throw new IdGenerationException("Id could not be generated for pojo. See logs for details.", e);
}
}
return document;
}
示例3: downGradeType
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
/**
* If the requested type is not registered within the class hierarchy it may still be persistable if a superclass is
* registered. But then we need to find the type that is in the set of registered types.
*
* @param type
* @param classHierarchyNodeForType
* @return
*/
private Type downGradeType(Type type, ClassHierarchyNode classHierarchyNodeForType) {
if (classHierarchyNodeForType == null) {
return type;
}
Class<?> clazz = classHierarchyNodeForType.getClazz();
// if the type is directly assignable, we can simply return the type
if (TypeUtils.isAssignable(clazz, type)) {
return type;
}
// now we need to downgrade type to clazz
if (clazz.getTypeParameters().length > 0) {
//if clazz has type parameters, we need to figure out the correct types
// TODO encoding with specific type arguments may work, but decoding into
// TODO the type (that is within the group of registered classes) would loose information, so maybe
// we should not try to infer the type arguments?
return TypeUtils.parameterize(clazz, TypeUtils.getTypeArguments(type, clazz));
} else {
return clazz;
}
}
示例4: resolve
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
/**
* Iterates over the list of codecResolvers and returns a PolymorphicCodec if match is found.
* Codecs eligible to encode/decode sub classes of polymorphic structures need to provide special functionality and
* can be registered during setup of the PojoCodecProvider {@link PojoCodecProvider.Builder#registerCodecResolver(CodecResolver[])}
*
* @param type the value type
* @param typeCodecRegistry codec registry that can handle any type including parameterizd types, generic arrays, etc
* @return ReflectionCodec if responsible resolver si found
*/
public synchronized <T> PolymorphicCodec<T> resolve(Type type, TypeCodecRegistry typeCodecRegistry) {
PolymorphicCodec<T> codec;
for (CodecResolver codecResolver : codecResolvers) {
codec = codecResolver.getCodec(type, typeCodecRegistry, codecConfiguration);
if (codec != null) {
return codec;
}
}
// enums are special - a PolymorphicCodec for enums can be build on the fly {@link EnumReflectionCodecWrapper}
if (TypeUtils.isAssignable(type, Enum.class)) {
return new EnumReflectionCodecWrapper(typeCodecRegistry.getCodec(type));
}
// fallback is BasicReflectionCodec
return new BasicReflectionCodec(type, typeCodecRegistry, codecConfiguration);
}
示例5: getGenericType
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
private Class<? extends Throwable> getGenericType(Class<? extends JsonApiExceptionMapper> mapper) {
Type[] types = mapper.getGenericInterfaces();
if (null == types || 0 == types.length ){
types = new Type[]{mapper.getGenericSuperclass()};
}
for (Type type : types) {
if (type instanceof ParameterizedType && (TypeUtils.isAssignable(((ParameterizedType) type).getRawType(),JsonApiExceptionMapper.class)
|| TypeUtils.isAssignable(((ParameterizedType) type).getRawType(),ExceptionMapper.class))) {
//noinspection unchecked
return (Class<? extends Throwable>) ((ParameterizedType) type).getActualTypeArguments()[0];
}
}
//Won't get in here
return null;
}
示例6: calculateExactType
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
private void calculateExactType(ParameterizedType type) {
logger.info("Calculating exact tyep for parameterized type " + type);
Class<?> rawClass = GenericTypeReflector.erase(type);
Type exactType = type;
for (VariableReference var : typeMap.get(type)) {
ParameterizedType currentType = (ParameterizedType) var.getType();
logger.info("Assigned variable of type: " + currentType);
Type candidateType = GenericTypeReflector.getExactSuperType(currentType,
rawClass);
logger.info("Resulting type: " + candidateType);
if (TypeUtils.isAssignable(candidateType, exactType)) {
exactType = candidateType;
}
}
logger.info("Result: " + exactType);
}
示例7: findAssignable
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
protected Converter findAssignable(Type src, Type target) {
if (TypeUtils.isAssignable(src, target)) {
return same;
}
return null;
}
示例8: getAssignableTypesWithinClassHierarchy
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
/**
* @param type the type for with sub types should be found
* @param classHierarchyNode the hierarchy of sub types
* @param validTypes a Set of found valid types so far
*/
private void getAssignableTypesWithinClassHierarchy(Type type, ClassHierarchyNode classHierarchyNode, Set<Type> validTypes) {
if (classHierarchyNode != null) {
Class<?> clazz = classHierarchyNode.getClazz();
Type matchingType = null;
// first check general assignability
// this does not mean that the parameterized clazz would be assignable to type since the parameter bounds may be wrong!
if (TypeUtils.isAssignable(clazz, type)) {
if (type instanceof ParameterizedType) {
matchingType = getMatchingType((ParameterizedType) type, clazz);
} else {
matchingType = clazz;
}
}
if (!clazz.isInterface() && matchingType != null) {
validTypes.add(matchingType);
}
// if type match, walk down children
if (matchingType != null) {
for (ClassHierarchyNode child : classHierarchyNode.getChildren()) {
getAssignableTypesWithinClassHierarchy(matchingType, child, validTypes);
}
}
}
}
示例9: get
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
@Override
public <T> Codec<T> get(Type type, TypeCodecRegistry typeCodecRegistry) {
// byte arrays are handled well by the mongo java driver
if (TypeUtils.isArrayType(type)) {
return new ArrayCodec(type, typeCodecRegistry);
} else if (type instanceof TypeVariable) {
throw new IllegalArgumentException("This registry (and probably no other one as well) can not handle generic type variables.");
} else if (type instanceof WildcardType) {
LOGGER.error("WildcardTypes are not yet supported. {}", type);
throw new NotImplementedException("WildcardTypes are not yet supported. " + type);
}
// the default codecs provided by the mongo driver lack the decode method, hence this redefinition
else if (Float.class.equals(type)) {
return (Codec<T>) FLOAT_CODEC;
} else if (Short.class.equals(type)) {
return (Codec<T>) SHORT_CODEC;
} else if (Byte.class.equals(type)) {
return (Codec<T>) BYTE_CODEC;
}
else if (TypeUtils.isAssignable(type, SpecialFieldsMap.class)) {
return new SpecialFieldsMapCodec(type, typeCodecRegistry);
}
// List ?
Codec<T> codec = ListTypeCodec.getCodecIfApplicable(type, typeCodecRegistry);
if (codec != null) {
return codec;
}
// Set ?
codec = SetTypeCodec.getCodecIfApplicable(type, typeCodecRegistry);
if (codec != null) {
return codec;
}
// Map ?
codec = MapTypeCodec.getCodecIfApplicable(type, typeCodecRegistry);
if (codec != null) {
return codec;
}
return null;
}
示例10: get
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
@Override
public <T> Codec<T> get(Type type, TypeCodecRegistry typeCodecRegistry) {
if (TypeUtils.isAssignable(type, CustomType.class)) {
return (Codec<T>) new CustomTypeCodec((ParameterizedType) type, typeCodecRegistry);
}
return null;
}
示例11: getMethodSpec
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
public static MethodTracepointSpec getMethodSpec(Class<?> cls, String methodName)
throws ClassNotFoundException {
MethodTracepointSpec.Builder b = MethodTracepointSpec.newBuilder();
b.setClassName(cls.getName());
b.setMethodName(methodName);
Method m = getMethod(cls, methodName);
for (Class<?> paramClass : m.getParameterTypes()) {
b.addParamClass(paramClass.getCanonicalName());
}
int paramCount = 0;
for (Type paramType : m.getGenericParameterTypes()) {
String paramName = String.format("$%d", ++paramCount);
if (TypeUtils.isArrayType(paramType)) {
Type arrayOfType = TypeUtils.getArrayComponentType(paramType);
String arrayOf = TypeUtils.toString(arrayOfType);
b.addAdviceArgBuilder().getMultiBuilder().setLiteral(paramName).setPostProcess("{}")
.setType(arrayOf);
} else if (TypeUtils.isAssignable(paramType, Collection.class)) {
ParameterizedType pt = (ParameterizedType) paramType;
Type collectionOfType = pt.getActualTypeArguments()[0]; // doesn't work if multiple type params, but
// good enough
String collectionOf = TypeUtils.toString(collectionOfType);
b.addAdviceArgBuilder().getMultiBuilder().setLiteral(paramName).setPostProcess("{}")
.setType(collectionOf);
} else {
b.addAdviceArgBuilder().setLiteral(paramName);
}
}
return b.build();
}
示例12: create
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
/** Create a tracepoint for the entry of the named method of the class.
* The name of the tracepoint will be the short class name and the method name,
* eg java.lang.String.format will have short name String.format
* Parameter types will be looked up, and if the method is overloaded, returns one of the methods.
* If any of the method arguments are arrays or collections, they will be exported as multi-variables
*/
public static MethodTracepoint create(Class<?> cls, String methodName, String... namesForMethodParameters) {
Where where = Where.ENTRY;
String tracepointName = String.format("%s.%s", cls.getSimpleName(), methodName);
// Find the method
Method m = getMethod(cls, methodName, namesForMethodParameters.length);
// Create the tracepoint
MethodTracepoint tracepoint = new MethodTracepoint(tracepointName, where, m);
// Export the arguments as variables
int paramCount = 0;
for (Type paramType : m.getGenericParameterTypes()) {
String exportAs = namesForMethodParameters[paramCount];
String literal = String.format("$%d", ++paramCount);
if (TypeUtils.isArrayType(paramType)) {
Type arrayOfType = TypeUtils.getArrayComponentType(paramType);
String arrayOf = TypeUtils.toString(arrayOfType);
tracepoint.addMultiExport(exportAs, literal, arrayOf);
} else if (TypeUtils.isAssignable(paramType, Collection.class)) {
ParameterizedType pt = (ParameterizedType) paramType;
Type collectionOfType = pt.getActualTypeArguments()[0];
String collectionOf = TypeUtils.toString(collectionOfType);
tracepoint.addMultiExport(exportAs, literal, collectionOf);
} else {
tracepoint.addExport(exportAs, literal);
}
}
return tracepoint;
}
示例13: isAssignable
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
/**
* <p>
* isAssignable
* </p>
*
* @param lhsType
* a {@link java.lang.reflect.Type} object.
* @param rhsType
* a {@link java.lang.reflect.Type} object.
* @return a boolean.
*/
public static boolean isAssignable(Type lhsType, Type rhsType) {
if (rhsType == null || lhsType == null)
return false;
try {
return TypeUtils.isAssignable(rhsType, lhsType);
} catch (Throwable e) {
logger.debug("Found unassignable type: " + e);
return false;
}
}
示例14: determineVariableFromParameter
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
private void determineVariableFromParameter(VariableReference parameter,
Type parameterType, Map<TypeVariable<?>, Type> typeMap) {
Map<TypeVariable<?>, Type> parameterTypeMap = getParameterType(parameterType,
parameter.getType());
logger.info("Resulting map: " + parameterTypeMap);
for (TypeVariable<?> typeVar : parameterTypeMap.keySet()) {
Type actualType = parameterTypeMap.get(typeVar);
if (typeMap.containsKey(typeVar)) {
logger.info("Variable is in map: " + typeVar);
Type currentType = typeMap.get(typeVar);
if (currentType == null
|| TypeUtils.isAssignable(actualType, currentType)) {
typeMap.put(typeVar, actualType);
} else {
logger.info("Not assignable: " + typeVar + " with bounds "
+ Arrays.asList(typeVar.getBounds()) + " and current type "
+ currentType + " from " + actualType);
logger.info(""
+ GenericTypeReflector.isSuperType(currentType, actualType));
logger.info("" + TypeUtils.isAssignable(actualType, typeVar));
}
} else {
logger.debug("Variable is not in map: " + typeVar);
typeMap.put(typeVar, actualType);
}
}
}
示例15: getMatchingType
import org.apache.commons.lang3.reflect.TypeUtils; //导入方法依赖的package包/类
/**
* @param parameterizedType the type to match to
* @param clazz the class for which the correct parametrization is to be found
* @return the parameterized type of clazz or null if no match
*/
private Type getMatchingType(ParameterizedType parameterizedType, Class<?> clazz) {
Type matchingType = null;
if (parameterizedType.getRawType().equals(clazz)) {
matchingType = parameterizedType;
} else {
// first find the superclass...may be an interface though
Type genericSuperclass = null;
if (ReflectionHelper.extractRawClass(parameterizedType).isInterface()) {
for (Type genericInterface : clazz.getGenericInterfaces()) {
if (TypeUtils.isAssignable(genericInterface, parameterizedType)) {
genericSuperclass = genericInterface;
break;
}
}
} else {
genericSuperclass = clazz.getGenericSuperclass();
}
if (genericSuperclass instanceof ParameterizedType) {
ParameterizedType parameterizedSuperClassType = (ParameterizedType) genericSuperclass;
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
Type[] superClassTypeArguments = parameterizedSuperClassType.getActualTypeArguments();
Map<String, Type> parameter = new HashMap<>();
for (int i = 0; i < superClassTypeArguments.length; i++) {
Type classTypeArgument = superClassTypeArguments[i];
if (classTypeArgument instanceof TypeVariable) {
if (actualTypeArguments[i] instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) actualTypeArguments[i];
parameter.put(((TypeVariable) classTypeArgument).getName(), wildcardType.getUpperBounds()[0]);
} else {
parameter.put(((TypeVariable) classTypeArgument).getName(), actualTypeArguments[i]);
}
}
}
TypeVariable<? extends Class<?>>[] typeParameters = clazz.getTypeParameters();
Type[] specifiedTypeArguments = new Type[typeParameters.length];
for (int i = 0; i < typeParameters.length; i++) {
Type inferredType = inferRealType(typeParameters[i], parameter);
if (TypeUtils.isAssignable(inferredType, typeParameters[i].getBounds()[0])) {
specifiedTypeArguments[i] = inferredType;
} else {
return null;
}
}
if (specifiedTypeArguments.length > 0) {
matchingType = TypeUtils.parameterize(clazz, specifiedTypeArguments);
} else {
matchingType = clazz;
}
} else {
LOGGER.debug("Type {} will be ignored as it has no generic superclass, but should have.", clazz);
}
}
return matchingType;
}