下面列出了java.lang.reflect.AnnotatedArrayType#java.lang.reflect.AnnotatedType 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void testReturnsEmptyAT() {
for (Class<?> toTest : nonNullTestData) {
tests++;
AnnotatedType res = toTest.getAnnotatedSuperclass();
if (res == null) {
failed++;
System.out.println(toTest + ".getAnnotatedSuperclass() returns 'null' should be non-null");
} else if (res.getAnnotations().length != 0) {
failed++;
System.out.println(toTest + ".getAnnotatedSuperclass() returns: "
+ Arrays.asList(res.getAnnotations()) + ", should be an empty AnnotatedType");
}
}
}
private void verifyArrayFieldTypeAnnotations(Class c)
throws NoSuchFieldException, NoSuchMethodException {
Annotation anno;
AnnotatedType at;
at = c.getDeclaredField("typeAnnotatedArray").getAnnotatedType();
anno = at.getAnnotations()[0];
verifyTestAnn(arrayTA[0], anno, "array1");
arrayTA[0] = anno;
for (int i = 1; i <= 3; i++) {
at = ((AnnotatedArrayType) at).getAnnotatedGenericComponentType();
anno = at.getAnnotations()[0];
verifyTestAnn(arrayTA[i], anno, "array" + (i + 1));
arrayTA[i] = anno;
}
}
private static void testReturnsEmptyAT() {
for (Class<?> toTest : nonNullTestData) {
tests++;
AnnotatedType res = toTest.getAnnotatedSuperclass();
if (res == null) {
failed++;
System.out.println(toTest + ".getAnnotatedSuperclass() returns 'null' should be non-null");
} else if (res.getAnnotations().length != 0) {
failed++;
System.out.println(toTest + ".getAnnotatedSuperclass() returns: "
+ Arrays.asList(res.getAnnotations()) + ", should be an empty AnnotatedType");
}
}
}
public static boolean containsTypeAnnotation(AnnotatedType type, Class<? extends Annotation> annotation) {
if (type.isAnnotationPresent(annotation)) {
return true;
}
if (type instanceof AnnotatedParameterizedType) {
AnnotatedParameterizedType parameterizedType = ((AnnotatedParameterizedType) type);
return Arrays.stream(parameterizedType.getAnnotatedActualTypeArguments())
.anyMatch(param -> containsTypeAnnotation(param, annotation));
}
if (type instanceof AnnotatedTypeVariable) {
AnnotatedTypeVariable variable = ((AnnotatedTypeVariable) type);
return Arrays.stream(variable.getAnnotatedBounds())
.anyMatch(bound -> containsTypeAnnotation(bound, annotation));
}
if (type instanceof AnnotatedWildcardType) {
AnnotatedWildcardType wildcard = ((AnnotatedWildcardType) type);
return Stream.concat(
Arrays.stream(wildcard.getAnnotatedLowerBounds()),
Arrays.stream(wildcard.getAnnotatedUpperBounds()))
.anyMatch(param -> containsTypeAnnotation(param, annotation));
}
return type instanceof AnnotatedArrayType && containsTypeAnnotation(((AnnotatedArrayType) type).getAnnotatedGenericComponentType(), annotation);
}
@SuppressWarnings("unchecked")
public <T, S> S convertOutput(T output, AnnotatedElement element, AnnotatedType type) {
if (output == null) {
return null;
}
// Transparently handle unexpected wrapped results. This enables elegant exception handling, partial results etc.
if (DataFetcherResult.class.equals(output.getClass()) && !DataFetcherResult.class.equals(resolver.getRawReturnType())) {
DataFetcherResult<?> result = (DataFetcherResult<?>) output;
if (result.getData() != null) {
Object convertedData = convert(result.getData(), element, type);
return (S) DataFetcherResult.newResult()
.data(convertedData)
.errors(result.getErrors())
.localContext(result.getLocalContext())
.mapRelativeErrors(result.isMapRelativeErrors())
.build();
}
}
return convert(output, element, type);
}
private Collection<Resolver> buildPropertyAccessors(Stream<Property> properties, ResolverBuilderParams params) {
MessageBundle messageBundle = params.getEnvironment().messageBundle;
AnnotatedType beanType = params.getBeanType();
Predicate<Member> mergedFilters = getFilters().stream().reduce(Predicate::and).orElse(ACCEPT_ALL);
return properties
.filter(prop -> isQuery(prop, params))
.filter(prop -> mergedFilters.test(prop.getField()) && mergedFilters.test(prop.getGetter()))
.filter(prop -> params.getInclusionStrategy().includeOperation(Arrays.asList(prop.getField(), prop.getGetter()), beanType))
.map(prop -> {
TypedElement element = propertyElementReducer.apply(new TypedElement(getFieldType(prop.getField(), params), prop.getField()), new TypedElement(getReturnType(prop.getGetter(), params), prop.getGetter()));
OperationInfoGeneratorParams infoParams = new OperationInfoGeneratorParams(element, beanType, params.getQuerySourceBeanSupplier(), messageBundle, OperationDefinition.Operation.QUERY);
return new Resolver(
messageBundle.interpolate(operationInfoGenerator.name(infoParams)),
messageBundle.interpolate(operationInfoGenerator.description(infoParams)),
messageBundle.interpolate(ReservedStrings.decode(operationInfoGenerator.deprecationReason(infoParams))),
element.isAnnotationPresent(Batched.class),
params.getQuerySourceBeanSupplier() == null ? new MethodInvoker(prop.getGetter(), beanType) : new FixedMethodInvoker(params.getQuerySourceBeanSupplier(), prop.getGetter(), beanType),
element,
argumentBuilder.buildResolverArguments(new ArgumentBuilderParams(prop.getGetter(), beanType, params.getInclusionStrategy(), params.getTypeTransformer(), params.getEnvironment())),
element.isAnnotationPresent(GraphQLComplexity.class) ? element.getAnnotation(GraphQLComplexity.class).value() : null
);
})
.collect(Collectors.toSet());
}
@SuppressWarnings("unchecked")
public static <T extends AnnotatedType> T transformType(T type, UnaryOperator<T> transformer) {
if (type instanceof AnnotatedArrayType) {
return (T) TypeFactory.arrayOf(transformer.apply((T) ((AnnotatedArrayType) type).getAnnotatedGenericComponentType()), type.getAnnotations());
}
if (type.getType() instanceof Class) {
return type;
}
if (type instanceof AnnotatedParameterizedType) {
AnnotatedParameterizedType parameterizedType = (AnnotatedParameterizedType) type;
AnnotatedType[] arguments = Arrays.stream(parameterizedType.getAnnotatedActualTypeArguments())
.map(param -> transformer.apply((T) param))
.toArray(AnnotatedType[]::new);
return (T) TypeFactory.parameterizedAnnotatedClass(GenericTypeReflector.erase(type.getType()), type.getAnnotations(), arguments);
}
throw new IllegalArgumentException("Can not find the mappable type for: " + type.getType().getTypeName());
}
public void checkAnnotations(AnnotatedType type, String expected) {
String actual = Arrays.asList(((AnnotatedParameterizedType) type)
.getAnnotations())
.toString()
+ "," +
Arrays.asList(((AnnotatedParameterizedType) type)
.getAnnotatedActualTypeArguments()[0].getAnnotations())
.toString();
if (!actual.equals(expected))
throw new AssertionError("Unexpected annotations" + actual);
}
protected OperationArgument buildResolverArgument(Parameter parameter, AnnotatedType parameterType, ArgumentBuilderParams builderParams) {
return new OperationArgument(
parameterType,
getArgumentName(parameter, parameterType, builderParams),
getArgumentDescription(parameter, parameterType, builderParams.getEnvironment().messageBundle),
defaultValue(parameter, parameterType, builderParams.getEnvironment()),
parameter,
parameter.isAnnotationPresent(GraphQLContext.class),
builderParams.getInclusionStrategy().includeArgumentForMapping(parameter, parameterType, builderParams.getDeclaringType())
);
}
@SuppressWarnings("unchecked")
private void derive(AnnotatedElement element, AnnotatedType type, List<DelegatingOutputConverter> derivers) {
derivers.stream()
.filter(deriver -> deriver.supports(element, type))
.findFirst()
.ifPresent(deriver -> registerDerivatives(element, type, deriver.getDerivedTypes(type), derivers));
}
private void verifyMapFieldTypeAnnotations(Class c)
throws NoSuchFieldException, NoSuchMethodException {
Annotation anno;
AnnotatedType atBase;
AnnotatedType atParameter;
atBase = c.getDeclaredField("typeAnnotatedMap").getAnnotatedType();
anno = atBase.getAnnotations()[0];
verifyTestAnn(mapTA[0], anno, "map1");
mapTA[0] = anno;
atParameter =
((AnnotatedParameterizedType) atBase).
getAnnotatedActualTypeArguments()[0];
anno = ((AnnotatedWildcardType) atParameter).getAnnotations()[0];
verifyTestAnn(mapTA[1], anno, "map2");
mapTA[1] = anno;
anno =
((AnnotatedWildcardType) atParameter).
getAnnotatedUpperBounds()[0].getAnnotations()[0];
verifyTestAnn(mapTA[2], anno, "map3");
mapTA[2] = anno;
atParameter =
((AnnotatedParameterizedType) atBase).
getAnnotatedActualTypeArguments()[1];
anno = ((AnnotatedParameterizedType) atParameter).getAnnotations()[0];
verifyTestAnn(mapTA[3], anno, "map4");
mapTA[3] = anno;
anno =
((AnnotatedParameterizedType) atParameter).
getAnnotatedActualTypeArguments()[0].getAnnotations()[0];
verifyTestAnn(mapTA[4], anno, "map5");
mapTA[4] = anno;
}
@Test
public void testSameClasses() throws AnnotationFormatException {
Annotation[] nonNull = new Annotation[] {TypeFactory.annotation(Nonnull.class, Collections.emptyMap())};
Annotation[] graphQLNonNull = new Annotation[] {TypeFactory.annotation(GraphQLNonNull.class, Collections.emptyMap())};
Annotation[] mergedAnnotations = new Annotation[] {nonNull[0], graphQLNonNull[0]};
AnnotatedType p1 = GenericTypeReflector.annotate(P.class, nonNull);
AnnotatedType p2 = GenericTypeReflector.annotate(P.class, graphQLNonNull);
AnnotatedType expected = GenericTypeReflector.annotate(P.class, mergedAnnotations);
AnnotatedType inferred = ClassUtils.getCommonSuperType(Arrays.asList(p1, p2));
assertTrue(GenericTypeReflector.equals(expected, inferred));
}
public JTypeVariable(D genericDeclaration, String name, Type[] bounds, AnnotatedType[] annotatedBounds, Annotation[] annotations, Annotation[] declaredAnnotations) {
this.genericDeclaration = genericDeclaration;
this.name = Objects.requireNonNull(name, "name");
this.bounds = bounds != null ? bounds : new Type[0];
this.annotatedBounds = annotatedBounds != null ? annotatedBounds : new AnnotatedType[0];
this.annotations = annotations != null ? annotations : new Annotation[0];
this.declaredAnnotations = declaredAnnotations != null ? declaredAnnotations : this.annotations;
}
private void verifyInnerFieldTypeAnnotations(Class c)
throws NoSuchFieldException, NoSuchMethodException {
AnnotatedType at = c.getDeclaredField("typeAnnotatedInner").getAnnotatedType();
Annotation anno = at.getAnnotations()[0];
verifyTestAnn(innerTA, anno, "inner");
innerTA = anno;
}
protected AnnotatedType getReturnType(Method method, ResolverBuilderParams params) {
try {
return params.getTypeTransformer().transform(ClassUtils.getReturnType(method, params.getBeanType()));
} catch (TypeMappingException e) {
throw TypeMappingException.ambiguousMemberType(method, params.getBeanType(), e);
}
}
@Override
public AnnotatedType getSubstituteType(AnnotatedType original) {
AnnotatedType component = ((AnnotatedArrayType) original).getAnnotatedGenericComponentType();
Class<?> raw = ClassUtils.getRawType(component.getType());
if (raw.isPrimitive()) {
component = GenericTypeReflector.annotate(GenericTypeReflector.box(raw), component.getAnnotations());
}
return TypeFactory.parameterizedAnnotatedClass(List.class, original.getAnnotations(), component);
}
@Test
public void testLists() throws AnnotationFormatException {
Annotation[] annotations = new Annotation[] {TypeFactory.annotation(GraphQLNonNull.class, Collections.emptyMap())};
AnnotatedType nonNullLongType = GenericTypeReflector.annotate(Long.class, annotations);
AnnotatedType doubleType = GenericTypeReflector.annotate(Double.class);
AnnotatedType nonNullNumberType = TypeFactory.parameterizedAnnotatedClass(Number.class, annotations);
AnnotatedType expected = TypeFactory.parameterizedAnnotatedClass(AbstractList.class, annotations, nonNullNumberType);
AnnotatedType list1 = TypeFactory.parameterizedAnnotatedClass(ArrayList.class, annotations, nonNullLongType);
AnnotatedType list2 = TypeFactory.parameterizedAnnotatedClass(LinkedList.class, new Annotation[0], doubleType);
AnnotatedType inferred = ClassUtils.getCommonSuperType(Arrays.asList(list1, list2));
assertTrue(GenericTypeReflector.equals(expected, inferred));
}
public ArgumentInjectorParams(Object input, boolean present, AnnotatedType type, AnnotatedType baseType, Parameter parameter, ResolutionEnvironment resolutionEnvironment) {
this.input = input;
this.present = present;
this.type = Objects.requireNonNull(type);
this.baseType = baseType;
this.parameter = parameter;
this.resolutionEnvironment = Objects.requireNonNull(resolutionEnvironment);
}
@Override
public Object convertOutput(Mono<T> original, AnnotatedType type, ResolutionEnvironment resolutionEnvironment) {
//For subscriptions, Mono<T> (Publisher<T>) should be returned directly
if (resolutionEnvironment.dataFetchingEnvironment.getParentType() == resolutionEnvironment.dataFetchingEnvironment.getGraphQLSchema().getSubscriptionType()) {
return original;
}
//For other operations it must be converted into a CompletableFuture<T>
return original.toFuture();
}
private List<ParameterConfiguration> _createParameterConfigs(final Class<?>[] paramTypes, final Annotation[][] paramAnnos,
final AnnotatedType[] annotatedParamTypes) {
final CollectionFactory cf = getCollectionFactory();
final List<ParameterConfiguration> paramCfgs = cf.createList(paramAnnos.length);
List<Check> paramChecks = cf.createList(2);
List<CheckExclusion> paramCheckExclusions = cf.createList(2);
// loop over all parameters of the current constructor
for (int i = 0; i < paramAnnos.length; i++) {
// loop over all annotations of the current constructor parameter
for (final Annotation anno : paramAnnos[i]) {
// check if the current annotation is a constraint annotation
if (anno.annotationType().isAnnotationPresent(Constraint.class)) {
paramChecks.add(initializeCheck(anno));
} else if (anno.annotationType().isAnnotationPresent(Constraints.class)) {
initializeChecks(anno, paramChecks);
} else if (anno.annotationType().isAnnotationPresent(Exclusion.class)) {
paramCheckExclusions.add(initializeExclusion(anno));
}
}
initializeGenericTypeChecks(paramTypes[i], annotatedParamTypes[i], paramChecks);
final ParameterConfiguration paramCfg = new ParameterConfiguration();
paramCfgs.add(paramCfg);
paramCfg.type = paramTypes[i];
if (paramChecks.size() > 0) {
paramCfg.checks = paramChecks;
paramChecks = cf.createList(2); // create a new list for the next parameter having checks
}
if (paramCheckExclusions.size() > 0) {
paramCfg.checkExclusions = paramCheckExclusions;
paramCheckExclusions = cf.createList(2); // create a new list for the next parameter having check exclusions
}
}
return paramCfgs;
}
@Override
@SuppressWarnings("unchecked")
public String generateTypeDescription(AnnotatedType type, MessageBundle messageBundle) {
Optional<String>[] descriptions = new Optional[]{
Optional.ofNullable(type.getAnnotation(GraphQLUnion.class))
.map(GraphQLUnion::description),
Optional.ofNullable(type.getAnnotation(GraphQLInterface.class))
.map(GraphQLInterface::description),
Optional.ofNullable(type.getAnnotation(GraphQLType.class))
.map(GraphQLType::description)
};
return messageBundle.interpolate(getFirstNonEmptyOrDefault(descriptions, () -> ""));
}
private void verifyMapFieldTypeAnnotations(Class c)
throws NoSuchFieldException, NoSuchMethodException {
Annotation anno;
AnnotatedType atBase;
AnnotatedType atParameter;
atBase = c.getDeclaredField("typeAnnotatedMap").getAnnotatedType();
anno = atBase.getAnnotations()[0];
verifyTestAnn(mapTA[0], anno, "map1");
mapTA[0] = anno;
atParameter =
((AnnotatedParameterizedType) atBase).
getAnnotatedActualTypeArguments()[0];
anno = ((AnnotatedWildcardType) atParameter).getAnnotations()[0];
verifyTestAnn(mapTA[1], anno, "map2");
mapTA[1] = anno;
anno =
((AnnotatedWildcardType) atParameter).
getAnnotatedUpperBounds()[0].getAnnotations()[0];
verifyTestAnn(mapTA[2], anno, "map3");
mapTA[2] = anno;
atParameter =
((AnnotatedParameterizedType) atBase).
getAnnotatedActualTypeArguments()[1];
anno = ((AnnotatedParameterizedType) atParameter).getAnnotations()[0];
verifyTestAnn(mapTA[3], anno, "map4");
mapTA[3] = anno;
anno =
((AnnotatedParameterizedType) atParameter).
getAnnotatedActualTypeArguments()[0].getAnnotations()[0];
verifyTestAnn(mapTA[4], anno, "map5");
mapTA[4] = anno;
}
@Override
public GraphQLNonNull toGraphQLInputType(AnnotatedType javaType, Set<Class<? extends TypeMapper>> mappersToSkip, TypeMappingEnvironment env) {
mappersToSkip.add(this.getClass());
GraphQLInputType inner = env.operationMapper.toGraphQLInputType(javaType, mappersToSkip, env);
return inner instanceof GraphQLNonNull ? (GraphQLNonNull) inner : new GraphQLNonNull(inner);
}
@Override
public boolean supports(AnnotatedType type) {
return ClassUtils.isSuperClass(Map.class, type) && !type.isAnnotationPresent(GraphQLScalar.class);
}
@Override
public boolean supports(AnnotatedElement element, AnnotatedType type) {
return supports(type);
}
public AnnotatedType[] getAnnotatedBounds() {
return null; // not used
}
@Override
public Collection<AnnotatedType> getInterfaces(AnnotatedType type) {
Map<Class<?>, AnnotatedType> interfaces = new HashMap<>();
collectInterfaces(type, interfaces);
return interfaces.values();
}
private void checkType(AnnotatedType type) {
if (type == null) {
throw TypeMappingException.unknownType();
}
checkType(type.getType());
}
@Override
public GraphQLInputObjectType toGraphQLInputType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
return objectTypeMapper.toGraphQLInputType(typeName, javaType, env);
}
@Override
public boolean supports(AnnotatedType type) {
return ClassUtils.isSuperClass(StrangelyNamedProperties.class, type);
}