List of usage examples for java.lang.reflect Field getGenericType
public Type getGenericType()
From source file:com.yahoo.egads.data.JsonEncoder.java
public static void fromJson(Object object, JSONObject json_obj) throws Exception { // for each json key-value, that has a corresponding variable in object ... for (Iterator k = json_obj.keys(); k.hasNext();) { String key = (String) k.next(); Object value = json_obj.get(key); // try to access object variable Field field = null; try {/*from w ww . j av a2s .c o m*/ field = object.getClass().getField(key); } catch (Exception e) { continue; } if (Modifier.isStatic(field.getModifiers())) { continue; } if (Modifier.isPrivate(field.getModifiers())) { continue; } Object member = field.get(object); if (json_obj.isNull(key)) { field.set(object, null); continue; // if variable is container... recurse } else if (member instanceof JsonAble) { ((JsonAble) member).fromJson((JSONObject) value); // if variable is an array... recurse on sub-objects } else if (member instanceof ArrayList) { // Depends on existance of ArrayList<T> template parameter, and T constructor with no arguments. // May be better to use custom fromJson() in member class. ArrayList memberArray = (ArrayList) member; JSONArray jsonArray = (JSONArray) value; // find array element constructor ParameterizedType arrayType = null; if (field.getGenericType() instanceof ParameterizedType) { arrayType = (ParameterizedType) field.getGenericType(); } for (Class c = member.getClass(); arrayType == null && c != null; c = c.getSuperclass()) { if (c.getGenericSuperclass() instanceof ParameterizedType) { arrayType = (ParameterizedType) c.getGenericSuperclass(); } } if (arrayType == null) { throw new Exception("could not find ArrayList element type for field 'key'"); } Class elementClass = (Class) (arrayType.getActualTypeArguments()[0]); Constructor elementConstructor = elementClass.getConstructor(); // for each element in JSON array ... append element to member array, recursively decode element for (int i = 0; i < jsonArray.length(); ++i) { Object element = elementConstructor.newInstance(); fromJson(element, jsonArray.getJSONObject(i)); memberArray.add(element); } // if variable is simple value... set } else if (field.getType() == float.class) { field.set(object, (float) json_obj.getDouble(key)); } else { field.set(object, value); } } }
From source file:it.unibas.spicy.persistence.object.operators.AnalyzeFields.java
private void generateCollectionOfReferences(ClassTree classTree, IClassNode currentNode, Field field) throws IllegalModelException { if (logger.isDebugEnabled()) logger.debug("Found a collection:" + field); ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); // list the actual type arguments Type[] targs = parameterizedType.getActualTypeArguments(); if (targs.length == 0 || targs.length > 1) { throw new IllegalModelException("Collection of non generic type: " + field); }// w w w . ja va 2 s.co m Class typeArgumentClass = (Class) targs[0]; String typeArgumentName = typeArgumentClass.getName(); if (logger.isDebugEnabled()) logger.debug("Generic type:" + typeArgumentName); IClassNode argumentTypeNode = classTree.get(typeArgumentName); if (argumentTypeNode == null) { throw new IllegalModelException("Illegal collection of references: " + field); } ReferenceProperty referenceProperty = new ReferenceProperty(field.getName(), field, currentNode, argumentTypeNode, Constants.MANY); currentNode.addReferenceProperty(referenceProperty); classTree.getReferences().add(referenceProperty); }
From source file:es.caib.sgtsic.ejb3.AbstractFacade.java
public boolean borrable(Object id) { T item = this.find(id); log.debug("Entramos a borrable " + item); if (item == null) { return false; }// w ww. j a va 2s.c o m log.debug("Entramos a borrable con no false " + item); for (Field f : entityClass.getDeclaredFields()) { boolean hasToManyAnnotations = (f.isAnnotationPresent(OneToMany.class)) || (f.isAnnotationPresent(ManyToMany.class)); if (hasToManyAnnotations) { Type type = f.getGenericType(); ParameterizedType pt = (ParameterizedType) type; List<Type> arguments = Arrays.asList(pt.getActualTypeArguments()); Class childEntityClass = null; for (Type argtype : arguments) { childEntityClass = (Class) argtype; break; } if (childEntityClass == null) continue; if (this.childrenCount(id, childEntityClass, entityClass) > 0) { log.debug("Cuenta positiva"); return false; } } } log.debug("Cuenta 0"); return true; }
From source file:com.github.reinert.jjschema.HyperSchemaGeneratorV4.java
@Override public <T> ObjectNode generateSchema(Class<T> type) throws TypeException { ObjectNode hyperSchema = null;//from w ww. j ava2s.co m Annotation path = type.getAnnotation(Path.class); if (path != null) { hyperSchema = generateHyperSchemaFromResource(type); } else { ObjectNode jsonSchema = (ObjectNode) jsonSchemaGenerator.generateSchema(type); if (jsonSchema != null) { if ("array".equals(jsonSchema.get("type").asText())) { if (!Collection.class.isAssignableFrom(type)) { ObjectNode items = (ObjectNode) jsonSchema.get("items"); // NOTE: Customized Iterable Class must declare the Collection object at first Field field = type.getDeclaredFields()[0]; ParameterizedType genericType = (ParameterizedType) field.getGenericType(); Class<?> genericClass = (Class<?>) genericType.getActualTypeArguments()[0]; ObjectNode hyperItems = transformJsonToHyperSchema(genericClass, (ObjectNode) items); jsonSchema.put("items", hyperItems); } hyperSchema = jsonSchema; } else if (jsonSchema.has("properties")) { hyperSchema = transformJsonToHyperSchema(type, jsonSchema); } else { hyperSchema = jsonSchema; } } } //TODO: When available by SchemaVersion, put the $schema attribute as the correct HyperSchema ref. return hyperSchema; }
From source file:de.ks.flatadocdb.defaults.ReflectionLuceneDocumentExtractor.java
protected boolean filterField(Field f) { boolean noStatic = !Modifier.isStatic(f.getModifiers()); if (noStatic) { Class<?> type = f.getType(); boolean validType = isValidBaseType(type); Type genericType = f.getGenericType(); if (!validType && Collection.class.isAssignableFrom(type) && genericType instanceof ParameterizedType) { Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments(); if (actualTypeArguments.length == 1 && actualTypeArguments[0] instanceof Class) { validType = isValidBaseType((Class<?>) actualTypeArguments[0]); }/*from w ww .ja v a2 s . c om*/ } if (!validType && TypeUtils.isArrayType(type)) { Type arrayComponentType = TypeUtils.getArrayComponentType(type); if (arrayComponentType instanceof Class) { validType = isValidBaseType((Class<?>) arrayComponentType); } } return validType; } return false; }
From source file:io.apiman.manager.api.es.EsMarshallingTest.java
/** * Fabricates a new instance of the given bean type. Uses reflection to figure * out all the fields and assign generated values for each. *//*from w w w . java 2 s. c o m*/ private static <T> T createBean(Class<T> beanClass) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException { T bean = beanClass.newInstance(); Map<String, String> beanProps = BeanUtils.describe(bean); for (String key : beanProps.keySet()) { try { Field declaredField = beanClass.getDeclaredField(key); Class<?> fieldType = declaredField.getType(); if (fieldType == String.class) { BeanUtils.setProperty(bean, key, StringUtils.upperCase(key)); } else if (fieldType == Boolean.class || fieldType == boolean.class) { BeanUtils.setProperty(bean, key, Boolean.TRUE); } else if (fieldType == Date.class) { BeanUtils.setProperty(bean, key, new Date(1)); } else if (fieldType == Long.class || fieldType == long.class) { BeanUtils.setProperty(bean, key, 17L); } else if (fieldType == Integer.class || fieldType == long.class) { BeanUtils.setProperty(bean, key, 11); } else if (fieldType == Set.class) { // Initialize to a linked hash set so that order is maintained. BeanUtils.setProperty(bean, key, new LinkedHashSet()); Type genericType = declaredField.getGenericType(); String typeName = genericType.getTypeName(); String typeClassName = typeName.substring(14, typeName.length() - 1); Class<?> typeClass = Class.forName(typeClassName); Set collection = (Set) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(bean, key); populateSet(collection, typeClass); } else if (fieldType == Map.class) { Map<String, String> map = new LinkedHashMap<String, String>(); map.put("KEY-1", "VALUE-1"); map.put("KEY-2", "VALUE-2"); BeanUtils.setProperty(bean, key, map); } else if (fieldType.isEnum()) { BeanUtils.setProperty(bean, key, fieldType.getEnumConstants()[0]); } else if (fieldType.getPackage() != null && fieldType.getPackage().getName().startsWith("io.apiman.manager.api.beans")) { Object childBean = createBean(fieldType); BeanUtils.setProperty(bean, key, childBean); } else { throw new IllegalAccessException( "Failed to handle property named [" + key + "] type: " + fieldType.getSimpleName()); } // String capKey = StringUtils.capitalize(key); // System.out.println(key);; } catch (NoSuchFieldException e) { // Skip it - there is not really a bean property with this name! } } return bean; }
From source file:info.archinnov.achilles.entity.parsing.PropertyParser.java
public <V> PropertyMeta parseListProperty(PropertyParsingContext context) { log.debug("Parsing property {} as list property of entity class {}", context.getCurrentPropertyName(), context.getCurrentEntityClass().getCanonicalName()); Class<?> entityClass = context.getCurrentEntityClass(); Field field = context.getCurrentField(); boolean timeUUID = isTimeUUID(context, field); Class<V> valueClass;//from w w w .j a va 2 s. com Type genericType = field.getGenericType(); valueClass = propertyHelper.inferValueClassForListOrSet(genericType, entityClass); Method[] accessors = entityIntrospector.findAccessors(entityClass, field); PropertyType type = propertyHelper.isLazy(field) ? LAZY_LIST : LIST; PropertyMeta listMeta = factory().objectMapper(context.getCurrentObjectMapper()).type(type) .propertyName(context.getCurrentPropertyName()) .entityClassName(context.getCurrentEntityClass().getCanonicalName()) .consistencyLevels(context.getCurrentConsistencyLevels()).accessors(accessors).timeuuid(timeUUID) .build(Void.class, valueClass); log.trace("Built list property meta for property {} of entity class {} : {}", listMeta.getPropertyName(), context.getCurrentEntityClass().getCanonicalName(), listMeta); return listMeta; }
From source file:info.archinnov.achilles.entity.parsing.PropertyParser.java
public <V> PropertyMeta parseSetProperty(PropertyParsingContext context) { log.debug("Parsing property {} as set property of entity class {}", context.getCurrentPropertyName(), context.getCurrentEntityClass().getCanonicalName()); Class<?> entityClass = context.getCurrentEntityClass(); Field field = context.getCurrentField(); boolean timeUUID = isTimeUUID(context, field); Class<V> valueClass;/*w w w . ja v a 2s.co m*/ Type genericType = field.getGenericType(); valueClass = propertyHelper.inferValueClassForListOrSet(genericType, entityClass); Method[] accessors = entityIntrospector.findAccessors(entityClass, field); PropertyType type = propertyHelper.isLazy(field) ? LAZY_SET : SET; PropertyMeta setMeta = factory().objectMapper(context.getCurrentObjectMapper()).type(type) .propertyName(context.getCurrentPropertyName()) .entityClassName(context.getCurrentEntityClass().getCanonicalName()) .consistencyLevels(context.getCurrentConsistencyLevels()).accessors(accessors).timeuuid(timeUUID) .build(Void.class, valueClass); log.trace("Built set property meta for property {} of entity class {} : {}", setMeta.getPropertyName(), context.getCurrentEntityClass().getCanonicalName(), setMeta); return setMeta; }
From source file:com.ethlo.geodata.restdocs.AbstractJacksonFieldSnippet.java
protected void handleSchema(final Class<?> type, final ObjectNode root, final ObjectNode definitions, FieldDescriptor desc, final Iterator<String> path) { ObjectNode lastNode = (ObjectNode) root.get("properties"); Class<?> lastField = type; while (path.hasNext() && lastNode != null && lastField != null) { final String p = StringUtils.replace(path.next(), "[]", ""); final Field f = FieldUtils.getField(lastField, p, true); final Class<?> field = f != null ? (Collection.class.isAssignableFrom(f.getType()) ? (Class<?>) ((ParameterizedType) f.getGenericType()).getActualTypeArguments()[0] : f.getType()) : null;//from w w w . ja v a2 s . c o m final JsonNode currentNode = lastNode.get(p); if (currentNode instanceof ObjectNode && field != null) { if (!path.hasNext()) { // Leaf of path definition, set description final String description = desc.getDescription().toString(); ((ObjectNode) currentNode).put("description", description); } final String typeDef = currentNode.path("type").asText(); if (!StringUtils.isNotEmpty(typeDef)) { handleRef(field, root, definitions, (ObjectNode) currentNode, desc, path); } } lastNode = currentNode instanceof ObjectNode ? (ObjectNode) currentNode : null; lastField = field; } }
From source file:cn.powerdash.libsystem.common.exception.AbstractExceptionHandler.java
/** * // w w w .j a va 2s. c o m * * @param rootClz * @param parseFieldName * @param matcher * @return * @throws SecurityException * @throws NoSuchFieldException */ private Class<?> getNextRootClass(Class<?> rootClz, final String parseFieldName, final boolean isFound) throws NoSuchFieldException, SecurityException { Class<?> rootClass = rootClz; if (rootClass != null) { try { Field parseField = rootClass.getDeclaredField(parseFieldName); if (isFound) { rootClass = (Class<?>) (((ParameterizedType) (parseField.getGenericType())) .getActualTypeArguments())[0]; } else { rootClass = parseField.getType(); } } catch (NoSuchFieldException ex) { try { final Class<?> superClass = rootClass.getSuperclass(); Field parseField = (superClass != null) ? superClass.getDeclaredField(parseFieldName) : null; if (parseField != null) { if (isFound) { rootClass = (Class<?>) (((ParameterizedType) (parseField.getGenericType())) .getActualTypeArguments())[0]; } else { rootClass = parseField.getType(); } } } catch (NoSuchFieldException ex1) { final Class<?> exsuperClass = rootClass.getSuperclass().getSuperclass(); Field parseField = (exsuperClass != null) ? exsuperClass.getDeclaredField(parseFieldName) : null; if (parseField != null) { if (isFound) { rootClass = (Class<?>) (((ParameterizedType) (parseField.getGenericType())) .getActualTypeArguments())[0]; } else { rootClass = parseField.getType(); } } } } LOGGER.debug("Next rootClass = " + rootClass); return rootClass; } else { return null; } }