本文整理汇总了Java中com.googlecode.gentyref.GenericTypeReflector类的典型用法代码示例。如果您正苦于以下问题:Java GenericTypeReflector类的具体用法?Java GenericTypeReflector怎么用?Java GenericTypeReflector使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
GenericTypeReflector类属于com.googlecode.gentyref包,在下文中一共展示了GenericTypeReflector类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: toRawData
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
/**
* Return the raw data into the right type. Generic type is also handled.
*
* @param data
* the data as String.
* @param expression
* the target expression.
* @return the data typed as much as possible to the target expression.
* @param <Y>
* The type of the {@link Expression}
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
protected static <Y> Y toRawData(final String data, final Expression<Y> expression) {
// Guess the right compile time type, including generic type
final Field field = (Field) ((SingularAttributePath<?>) expression).getAttribute().getJavaMember();
final Class<?> entity = ((SingularAttributePath<?>) expression).getPathSource().getJavaType();
final Class<?> expressionType = (Class<?>) GenericTypeReflector.getExactFieldType(field, entity);
// Bind the data to the correct type
final Y result;
if (expressionType == Date.class) {
// For Date, only milliseconds are managed
result = (Y) new Date(Long.parseLong(data));
} else if (expressionType.isEnum()) {
// Manage Enum type
result = (Y) toEnum(data, (Expression<Enum>) expression);
} else {
// Involve bean utils to convert the data
result = (Y) CONVERTER.convert(data, expressionType);
}
return result;
}
示例2: call
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
@Override
public List<GraphQLArgument> call(@Nullable Field field, Method method, Class declaringClass, Annotation annotation) {
// if same annotation is detected on both field and getter we fail. Only one annotation is allowed. We can talk about having precedence logic later.
if (method.isAnnotationPresent(annotation.annotationType()) && field != null && field.isAnnotationPresent(annotation.annotationType())) {
throw new IllegalArgumentException("Conflict: GraphQL Annotations can't be added to both field and getter. Pick one for "+
annotation.annotationType() + " on " + field.getName() + " and " + method.getName());
}
Type returnType = GenericTypeReflector.getExactReturnType(method, declaringClass);
if (returnType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) returnType;
Type containerType = parameterizedType.getRawType();
if (Collection.class.isAssignableFrom((Class) containerType)) {
List<GraphQLArgument> arguments = new ArrayList<>();
arguments.add(newArgument().name(GlitrForwardPagingArguments.FIRST).type(GraphQLInt).build());
arguments.add(newArgument().name(GlitrForwardPagingArguments.AFTER).type(GraphQLString).build());
return arguments;
}
}
return new ArrayList<>();
}
示例3: getGraphQLFieldDefinition
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
private GraphQLFieldDefinition getGraphQLFieldDefinition(Class clazz, Method method) {
String name = ReflectionUtil.sanitizeMethodName(method.getName());
String description = ReflectionUtil.getDescriptionFromAnnotatedElement(method);
if (description != null && description.equals(GlitrDescription.DEFAULT_DESCRIPTION)) {
ReflectionUtil.getDescriptionFromAnnotatedField(clazz, method);
}
Type fieldType = GenericTypeReflector.getExactReturnType(method, clazz);
GraphQLType type = typeRegistry.convertToGraphQLOutputType(fieldType, name, true);
if (type instanceof GraphQLTypeReference) {
typeRegistry.getRegistry().putIfAbsent((Class) fieldType, type);
}
boolean nullable = ReflectionUtil.isAnnotatedElementNullable(method);
if (!nullable || name.equals("id")) {
type = new GraphQLNonNull(type);
}
return newFieldDefinition()
.name(name)
.description(description)
.dataFetcher(CompositeDataFetcherFactory.create(Collections.singletonList(new PropertyDataFetcher(name))))
.type((GraphQLOutputType) type)
.build();
}
示例4: retrieveGraphQLOutputType
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
public GraphQLOutputType retrieveGraphQLOutputType(Class declaringClass, Method method) {
GraphQLOutputType graphQLOutputType;
String name = ReflectionUtil.sanitizeMethodName(method.getName());
graphQLOutputType = getGraphQLOutputTypeFromAnnotationsOnGetter(declaringClass, method);
graphQLOutputType = getGraphQLOutputTypeFromAnnotationsOnField(declaringClass, method, graphQLOutputType, name);
// default OutputType
if (graphQLOutputType == null) {
graphQLOutputType = (GraphQLOutputType) convertToGraphQLOutputType(GenericTypeReflector.getExactReturnType(method, declaringClass), name);
// is this an optional field
boolean nullable = ReflectionUtil.isAnnotatedElementNullable(method);
if (!nullable || name.equals("id")) {
graphQLOutputType = new GraphQLNonNull(graphQLOutputType);
}
}
return graphQLOutputType;
}
示例5: setQueryParameters
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
private void setQueryParameters(final UriBuilder uriBuilder, Scope scope, Object[] parameters) {
Type[] realParamTypes = GenericTypeReflector.getExactParameterTypes(scope
.getInvokedMethod(), scope.getInvokedClass());
visitAnnotations((parameter, parameterIndex, annotation) -> {
if (annotation instanceof QueryParam && parameter != null) {
final String parameterName = ((QueryParam) annotation).value();
if (parameter instanceof Iterable) {
uriBuilder.queryParam(parameterName, Iterables.toArray((Iterable) parameter, Object.class));
} else {
uriBuilder.queryParam(parameterName, parameter.toString());
}
} else if (annotation instanceof BeanParam && parameter != null) {
if (realParamTypes[parameterIndex] instanceof Class<?>) {
BeanParamExtractor beanParamExtractor = new BeanParamExtractor();
Map<String, Object[]> queryParameter = beanParamExtractor.getQueryParameters(
parameter);
queryParameter.forEach((uriBuilder::queryParam));
}
}
}, scope.getInvokedMethod(), parameters);
}
示例6: inferCollection
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
private static GenericType inferCollection(Type type) {
CollectionGenericType ret = new CollectionGenericType();
Type valueType = GenericTypeReflector.getTypeParameter(type, Collection.class.getTypeParameters()[0]);
ret.isInferred = valueType != null;
if (valueType == null) {
return ret;
}
ret.valueType = GenericTypeReflector.erase(valueType);
if (Map.class.isAssignableFrom(ret.valueType)) {
ret.nestedGenericValue = inferMap(valueType);
} else if (Collection.class.isAssignableFrom(ret.valueType)) {
ret.nestedGenericValue = inferCollection(valueType);
}
return ret;
}
示例7: createPrimitive
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
/**
* Create and return a new primitive variable
*
* @param test
* @param position
* @param recursionDepth
* @return
* @throws ConstructionFailedException
*/
private VariableReference createPrimitive(TestCase test, GenericClass clazz,
int position, int recursionDepth) throws ConstructionFailedException {
// Special case: we cannot instantiate Class<Class<?>>
if (clazz.isClass()) {
if (clazz.hasWildcardOrTypeVariables()) {
logger.debug("Getting generic instantiation of class");
clazz = clazz.getGenericInstantiation();
logger.debug("Chosen: " + clazz);
}
Type parameterType = clazz.getParameterTypes().get(0);
if (!(parameterType instanceof WildcardType) && GenericTypeReflector.erase(parameterType).equals(Class.class)) {
throw new ConstructionFailedException(
"Cannot instantiate a class with a class");
}
}
Statement st = PrimitiveStatement.getRandomStatement(test, clazz,
position);
VariableReference ret = test.addStatement(st, position);
ret.setDistance(recursionDepth);
return ret;
}
示例8: getExactReturnType
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
/**
* Returns the exact return type of the given method in the given type. This
* may be different from <tt>m.getGenericReturnType()</tt> when the method
* was declared in a superclass, or <tt>type</tt> has a type parameter that
* is used in the return type, or <tt>type</tt> is a raw type.
*/
protected Type getExactReturnType(Method m, Type type) throws IllegalArgumentException{
Inputs.checkNull(m,type);
Type returnType = m.getGenericReturnType();
Type exactDeclaringType = GenericTypeReflector.getExactSuperType(GenericTypeReflector.capture(type),
m.getDeclaringClass());
if (exactDeclaringType == null) { // capture(type) is not a subtype of m.getDeclaringClass()
logger.info("The method " + m + " is not a member of type " + type
+ " - declared in " + m.getDeclaringClass());
return m.getReturnType();
}
//if (exactDeclaringType.equals(type)) {
// logger.debug("Returntype: " + returnType + ", " + exactDeclaringType);
// return returnType;
//}
return mapTypeParameters(returnType, exactDeclaringType);
}
示例9: getExactParameterTypes
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
/**
* Returns the exact parameter types of the given method in the given type.
* This may be different from <tt>m.getGenericParameterTypes()</tt> when the
* method was declared in a superclass, or <tt>type</tt> has a type
* parameter that is used in one of the parameters, or <tt>type</tt> is a
* raw type.
*/
public Type[] getExactParameterTypes(Method m, Type type) {
Type[] parameterTypes = m.getGenericParameterTypes();
Type exactDeclaringType = GenericTypeReflector.getExactSuperType(GenericTypeReflector.capture(type),
m.getDeclaringClass());
if (exactDeclaringType == null) { // capture(type) is not a subtype of m.getDeclaringClass()
logger.info("The method " + m + " is not a member of type " + type
+ " - declared in " + m.getDeclaringClass());
return m.getParameterTypes();
}
Type[] result = new Type[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
result[i] = mapTypeParameters(parameterTypes[i], exactDeclaringType);
}
return result;
}
示例10: mapTypeParameters
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
/**
* Maps type parameters in a type to their values.
*
* @param toMapType
* Type possibly containing type arguments
* @param typeAndParams
* must be either ParameterizedType, or (in case there are no
* type arguments, or it's a raw type) Class
* @return toMapType, but with type parameters from typeAndParams replaced.
*/
protected Type mapTypeParameters(Type toMapType, Type typeAndParams) {
if (isMissingTypeParameters(typeAndParams)) {
logger.debug("Is missing type parameters, so erasing types");
return GenericTypeReflector.erase(toMapType);
} else {
VarMap varMap = new VarMap();
Type handlingTypeAndParams = typeAndParams;
while (handlingTypeAndParams instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) handlingTypeAndParams;
Class<?> clazz = (Class<?>) pType.getRawType(); // getRawType should always be Class
varMap.addAll(clazz.getTypeParameters(), pType.getActualTypeArguments());
handlingTypeAndParams = pType.getOwnerType();
}
varMap.addAll(getTypeVariableMap());
return varMap.map(toMapType);
}
}
示例11: getExactParameterTypes
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
/**
* Returns the exact parameter types of the given method in the given type.
* This may be different from <tt>m.getGenericParameterTypes()</tt> when the
* method was declared in a superclass, or <tt>type</tt> has a type
* parameter that is used in one of the parameters, or <tt>type</tt> is a
* raw type.
*/
public Type[] getExactParameterTypes(Constructor<?> m, Type type) {
Type[] parameterTypes = m.getGenericParameterTypes();
Type exactDeclaringType = GenericTypeReflector.getExactSuperType(GenericTypeReflector.capture(type),
m.getDeclaringClass());
if (exactDeclaringType == null) { // capture(type) is not a subtype of m.getDeclaringClass()
throw new IllegalArgumentException("The constructor " + m
+ " is not a member of type " + type);
}
Type[] result = new Type[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
result[i] = mapTypeParameters(parameterTypes[i], exactDeclaringType);
}
return result;
}
示例12: calculateExactType
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的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);
}
示例13: fromJSON
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
public @CheckForNull <T> T fromJSON(@CheckForNull Object from, Type toType, double version, @CheckForNull AnnotatedElement toAnnos, @CheckForNull Object enclosing) throws SourJsonException {
if (from == null)
return null;
Class<?> toClass = GenericTypeReflector.erase(toType);
TypeAndAnnos info = new TypeAndAnnos(toType, toAnnos);
if (toClass.isPrimitive()) {
toClass = SJUtils.PRIMITIVES_TO_WRAPPERS.get(toClass);
toType = toClass;
}
if (from instanceof JSONObject && ((JSONObject)from).containsKey("!type")) {
String className = (String)((JSONObject)from).get("!type");
try {
info.type = Class.forName(className);
}
catch (ClassNotFoundException e) {
throw new SourJsonException("Could not find class " + className);
}
}
return (T)tcache.getTranslater(info, this).deserialize(from, enclosing, version, this);
}
示例14: bindProperty
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
/**
* Binds {@code property} with {@code propertyType} to the field in the
* {@code objectWithMemberFields} instance using {@code memberField} as a
* reference to a member.
*
* @param objectWithMemberFields
* the object that contains (Java) member fields to build and bind
* @param memberField
* reference to a member field to bind
* @param propertyName
* property name to bind
* @param propertyType
* type of the property
* @return {@code true} if property is successfully bound
*/
protected boolean bindProperty(Object objectWithMemberFields, Field memberField, String propertyName,
Class<?> propertyType) {
log.log(Level.INFO, "Binding property, field={0}, property={1}",
new Object[] { memberField.getName(), propertyName });
Type valueType = GenericTypeReflector.getTypeParameter(memberField.getGenericType(),
HasValue.class.getTypeParameters()[0]);
if (valueType == null) {
throw new IllegalStateException(
String.format("Unable to detect value type for the member '%s' in the " + "class '%s'.",
memberField.getName(), objectWithMemberFields.getClass().getName()));
}
HasValue<?> field;
// Get the field from the object
try {
field = (HasValue<?>) ReflectTools.getJavaFieldValue(objectWithMemberFields, memberField, HasValue.class);
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
log.log(Level.INFO, "Not able to determine type of field");
// If we cannot determine the value, just skip the field
return false;
}
bind(field, propertyName);
return true;
}
示例15: populateBean
import com.googlecode.gentyref.GenericTypeReflector; //导入依赖的package包/类
/**
* Populates a bean instance with random values for properties of a supported types of RandomGenerators.
*
* @param bean bean to be populated
* @param <T> Type of the bean to be populated
* @return populated bean, the original object is populated, so the returned object is the same instance as provided as parameter.
* @see com.namics.commons.random.generator.RandomGenerator
* @see RandomData#random(Class, Object...)
*/
public static <T> T populateBean(T bean) {
Class<?> beanClass = bean.getClass();
List<PropertyDescriptor> propertyDescriptors = BeanUtils.getPropertyDescriptors(beanClass);
for (PropertyDescriptor descriptor : propertyDescriptors) {
Class<?> propertyType = descriptor.getPropertyType();
if (Class.class != propertyType) {
try {
Method writeMethod = descriptor.getWriteMethod();
if (writeMethod != null) {
LOG.info("Property {} ", descriptor);
String propertyName = descriptor.getName();
Type[] genericParameterTypes = writeMethod.getGenericParameterTypes();
Type genericFieldType = genericParameterTypes[0];
Object random;
if (beanClass == propertyType) {
random = bean;
} else if (genericFieldType instanceof TypeVariable) {
Type[] exactGenericTypes = GenericTypeReflector.getExactParameterTypes(writeMethod, beanClass);
random = random(exactGenericTypes[0], propertyName);
} else if (genericFieldType instanceof ParameterizedType) {
random = random(genericFieldType, propertyName);
} else {
random = random(propertyType, propertyName);
}
if (random != null) {
makeAccessible(writeMethod);
writeMethod.invoke(bean, random);
}
}
} catch (Throwable e) {
LOG.info("Property {} could not be processed", descriptor, e);
}
}
}
return bean;
}