本文整理汇总了Java中org.apache.commons.lang3.reflect.TypeUtils类的典型用法代码示例。如果您正苦于以下问题:Java TypeUtils类的具体用法?Java TypeUtils怎么用?Java TypeUtils使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
TypeUtils类属于org.apache.commons.lang3.reflect包,在下文中一共展示了TypeUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getCodecRegistry
import org.apache.commons.lang3.reflect.TypeUtils; //导入依赖的package包/类
@Bean()
public static CodecRegistry getCodecRegistry() {
return CodecRegistries.fromRegistries(
CodecRegistries.fromProviders(
new EnumCodecProvider(),
PojoCodecProvider.builder()
.register(CodecResolverTest.class)
.registerCodecResolver((CodecResolver) (type, typeCodecRegistry, codecConfiguration) -> {
if (TypeUtils.isAssignable(type, Base.class)) {
return new DocumentCodec((Class<? extends Base>) type, typeCodecRegistry, codecConfiguration);
}
return null;
})
.build()
),
MongoClient.getDefaultCodecRegistry());
}
示例2: 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);
}
示例3: createSignature
import org.apache.commons.lang3.reflect.TypeUtils; //导入依赖的package包/类
private static Signature createSignature(final Object input, final Type type, final Map<TypeVariable<?>, Type> typeArgs, final boolean isInput) {
final Class clazz = getTypeClass(type, typeArgs);
if (Tuple.class.isAssignableFrom(clazz)) {
final TypeVariable[] tupleTypes = getTypeClass(type, typeArgs).getTypeParameters();
final Map<TypeVariable<?>, Type> classTypeArgs = TypeUtils.getTypeArguments(type, clazz);
Collection<? extends Type> types = TypeUtils.getTypeArguments(type, clazz).values();
Class[] classes = new Class[types.size()];
int i = 0;
for (final TypeVariable tupleType : tupleTypes) {
classes[i++] = getTypeClass(classTypeArgs.get(tupleType), typeArgs);
}
return new TupleSignature(input, clazz, classes, isInput);
}
return new SingletonSignature(input, clazz, isInput);
}
示例4: 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;
}
示例5: 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;
}
}
示例6: inferRealType
import org.apache.commons.lang3.reflect.TypeUtils; //导入依赖的package包/类
/**
* Assume the following class declaration:
* <pre>
* {@code
* static class AList<P1, P2 extends Map<P1, Long>> implements AInterface<P1> {}
* }
* </pre>
* <p>
* For a given clazzTypeParameter ({@link TypeVariable} P1) and the map P1 -> Integer.class
* a new Type {@code Integer} is returned.
* <p>
* For a given clazzTypeParameter ({@link TypeVariable} P2) and the map P1 -> Integer.class
* a new Type {@code Map<Integer, Long>} is returned.
*
* @param clazzTypeParameter The TypeVariable of a given class
* @param superClassTypeMap the map of resolved values
* @return a recursively resolved type
*/
private static Type inferRealType(Type clazzTypeParameter, Map<String, Type> superClassTypeMap) {
if (clazzTypeParameter instanceof ParameterizedType) {
ParameterizedType bound = (ParameterizedType) clazzTypeParameter;
List<Type> typeList = new ArrayList<>();
for (int i = 0; i < bound.getActualTypeArguments().length; i++) {
typeList.add(inferRealType(bound.getActualTypeArguments()[i], superClassTypeMap));
}
return TypeUtils.parameterizeWithOwner(bound.getOwnerType(), (Class<?>) bound.getRawType(), typeList.toArray(new Type[0]));
} else if (clazzTypeParameter instanceof TypeVariable) {
TypeVariable typeVariable = (TypeVariable) clazzTypeParameter;
Type newType = superClassTypeMap.get(typeVariable.getName());
if (newType != null) {
return newType;
} else {
return inferRealType(typeVariable.getBounds()[0], superClassTypeMap);
}
}
return clazzTypeParameter;
}
示例7: 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);
}
示例8: downGradeTypeTest
import org.apache.commons.lang3.reflect.TypeUtils; //导入依赖的package包/类
@Test
public void downGradeTypeTest() {
TypesModel typesModel = new TypesModel(new HashSet<>(
Arrays.asList(
ModelClassBase.class,
ModelClassWithTypeParameter.class,
ModelClassWithoutTypeParameter.class
)), null, null);
assertThat(typesModel.getAssignableTypesWithinClassHierarchy(NonModelClassWithoutTypeParameter.class),
IsIterableContainingInAnyOrder.containsInAnyOrder(ModelClassWithoutTypeParameter.class));
assertThat(typesModel.getAssignableTypesWithinClassHierarchy(TypeUtils.parameterize(NonModelClassWithTypeParameter.class, Float.class)),
IsIterableContainingInAnyOrder.containsInAnyOrder(
TypeUtils.parameterize(ModelClassWithTypeParameter.class, Float.class, Date.class)));
assertThat(typesModel.getAssignableTypesWithinClassHierarchy(NonModelClassWithoutTypeParameterExtendingModelClassWithTypeParameter.class),
IsIterableContainingInAnyOrder.containsInAnyOrder(
TypeUtils.parameterize(ModelClassWithTypeParameter.class, BigInteger.class, Date.class)));
assertThat(typesModel.getAssignableTypesWithinClassHierarchy(NonModelClassWithTypeParameterExtendingNonModelClass.class),
IsIterableContainingInAnyOrder.containsInAnyOrder(
TypeUtils.parameterize(ModelClassWithTypeParameter.class, Float.class, Date.class)));
}
示例9: getAssignableTypesWithinClassHierarchy
import org.apache.commons.lang3.reflect.TypeUtils; //导入依赖的package包/类
@Test
public void getAssignableTypesWithinClassHierarchy() throws Exception {
assertThat(typesModel.getAssignableTypesWithinClassHierarchy(TypeUtils.parameterize(A.class, Integer.class)),
IsIterableContainingInAnyOrder.containsInAnyOrder(
TypeUtils.parameterize(A.class, Integer.class)));
assertThat(typesModel.getAssignableTypesWithinClassHierarchy(TypeUtils.parameterize(XY.class, Float.class)),
IsIterableContainingInAnyOrder.containsInAnyOrder(
TypeUtils.parameterize(A.class, Float.class)));
assertThat(typesModel.getAssignableTypesWithinClassHierarchy(TypeUtils.parameterize(XY.class, Integer.class)),
IsIterableContainingInAnyOrder.containsInAnyOrder(
TypeUtils.parameterize(A.class, Integer.class),
AAX.class));
assertThat(typesModel.getAssignableTypesWithinClassHierarchy(TypeUtils.parameterize(XY.class, BigInteger.class)),
IsIterableContainingInAnyOrder.containsInAnyOrder(
TypeUtils.parameterize(A.class, BigInteger.class),
TypeUtils.parameterize(AA.class, BigInteger.class),
AAB.class,
AAA.class,
ABX.class,
AAAA.class));
}
示例10: getCodecRegistry
import org.apache.commons.lang3.reflect.TypeUtils; //导入依赖的package包/类
@Bean()
public static CodecRegistry getCodecRegistry() {
return CodecRegistries.fromRegistries(
CodecRegistries.fromProviders(
new EnumCodecProvider(),
PojoCodecProvider.builder()
.register(Pojo.class.getPackage().getName())
.registerCodecResolver((CodecResolver) (type, typeCodecRegistry, codecConfiguration) -> {
if (TypeUtils.isAssignable(type, CustomId.class)) {
return new CustomIdCodec((Class<CustomId>)type, typeCodecRegistry, codecConfiguration);
}
return null;
}).build()
),
MongoClient.getDefaultCodecRegistry());
}
示例11: 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;
}
示例12: main
import org.apache.commons.lang3.reflect.TypeUtils; //导入依赖的package包/类
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
int[] a = new int[20];
Class clazz = a.getClass();
// System.out.println(clazz.newInstance());
System.out.println(clazz.isArray());
System.out.println(TypeUtils.getArrayComponentType(clazz));
System.out.println(clazz);
Object arr = Array.newInstance(clazz.getComponentType(), 20);
System.out.println(arr);
List<Integer> d = new ArrayList<>();
clazz = d.getClass();
System.out.println(d.getClass().getGenericSuperclass());
System.out.println(d.getClass().getGenericInterfaces()[0]);
ParameterizedType t = (ParameterizedType) clazz.getGenericSuperclass();
System.out.println(t.getActualTypeArguments()[0]);
}
示例13: 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);
}
示例14: registerAggregateFactories
import org.apache.commons.lang3.reflect.TypeUtils; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private <T> void registerAggregateFactories(
final RegistrableAggregateSnaphotter snapshotter) {
Set<Annotation> qualifiers = ImmutableSet.copyOf(getQualifiers());
for (AggregateRootInfo aggregateRoot : aggregateRootsInfo) {
if (aggregateRoot.matchQualifiers(QualifierType.SNAPSHOTTER, qualifiers)) {
Set<Annotation> factoryQualifiers = aggregateRoot
.getQualifiers(QualifierType.REPOSITORY);
Type type = TypeUtils.parameterize(EventSourcingRepository.class,
aggregateRoot.getType());
EventSourcingRepository<T> repository = (EventSourcingRepository<T>) CdiUtils
.getReference(getBeanManager(), type, factoryQualifiers);
if (repository != null) {
snapshotter.registerAggregateFactory(repository.getAggregateFactory());
}
new EventCountSnapshotTriggerDefinition(snapshotter, 10);
}
}
}
示例15: registerRepositories
import org.apache.commons.lang3.reflect.TypeUtils; //导入依赖的package包/类
@SuppressWarnings({ "unchecked" })
protected <T> void registerRepositories(X commandBus) {
final Set<Annotation> qualifiers = ImmutableSet.copyOf(getQualifiers());
for (AggregateRootInfo aggregateRootInfo : aggregateRootsInfo) {
if (aggregateRootInfo.matchQualifiers(QualifierType.COMMAND_BUS, qualifiers)) {
Class<T> aggregateType = (Class<T>) aggregateRootInfo.getType();
ParameterizedType repositoryType = TypeUtils.parameterize(EventSourcingRepository.class,
aggregateType);
EventSourcingRepository<T> repository = (EventSourcingRepository<T>) CdiUtils.getReference(
getBeanManager(), repositoryType, aggregateRootInfo.getQualifiers(QualifierType.REPOSITORY));
AggregateAnnotationCommandHandler<?> aggregateAnnotationCommandHandler = new AggregateAnnotationCommandHandler<>(aggregateType,
repository);
aggregateAnnotationCommandHandler.subscribe(commandBus);
if (commandBus instanceof DisruptorCommandBus) {
((DisruptorCommandBus) commandBus).createRepository(repository.getAggregateFactory());
}
}
}
}