@SuppressWarnings("rawtypes") protected Object saveObject( Object obj, Field field, ConfigurationSection cs, String path, int depth) throws Exception { Class clazz = getClassAtDepth(field.getGenericType(), depth); if (ConfigObject.class.isAssignableFrom(clazz) && isConfigObject(obj)) { return getConfigObject((ConfigObject) obj, path, cs); } else if (Location.class.isAssignableFrom(clazz) && isLocation(obj)) { return getLocation((Location) obj); } else if (Vector.class.isAssignableFrom(clazz) && isVector(obj)) { return getVector((Vector) obj); } else if (Map.class.isAssignableFrom(clazz) && isMap(obj)) { return getMap((Map) obj, field, cs, path, depth); } else if (clazz.isEnum() && isEnum(clazz, obj)) { return getEnum((Enum) obj); } else if (List.class.isAssignableFrom(clazz) && isList(obj)) { Class subClazz = getClassAtDepth(field.getGenericType(), depth + 1); if (ConfigObject.class.isAssignableFrom(subClazz) || Location.class.isAssignableFrom(subClazz) || Vector.class.isAssignableFrom(subClazz) || Map.class.isAssignableFrom(subClazz) || List.class.isAssignableFrom(subClazz) || subClazz.isEnum()) { return getList((List) obj, field, cs, path, depth); } else { return obj; } } else { return obj; } }
public static Class getFieldGenericType(Field field) { if (ParameterizedType.class.isAssignableFrom(field.getGenericType().getClass())) { ParameterizedType genericType = (ParameterizedType) field.getGenericType(); return (Class) genericType.getActualTypeArguments()[0]; } return Void.class; }
@SuppressWarnings("rawtypes") protected Object loadObject(Field field, ConfigurationSection cs, String path, int depth) throws Exception { Class clazz = getClassAtDepth(field.getGenericType(), depth); if (ConfigObject.class.isAssignableFrom(clazz) && isConfigurationSection(cs.get(path))) { return getConfigObject(clazz, cs.getConfigurationSection(path)); } else if (Location.class.isAssignableFrom(clazz) && isJSON(cs.get(path))) { return getLocation((String) cs.get(path)); } else if (Vector.class.isAssignableFrom(clazz) && isJSON(cs.get(path))) { return getVector((String) cs.get(path)); } else if (Map.class.isAssignableFrom(clazz) && isConfigurationSection(cs.get(path))) { return getMap(field, cs.getConfigurationSection(path), path, depth); } else if (clazz.isEnum() && isString(cs.get(path))) { return getEnum(clazz, (String) cs.get(path)); } else if (List.class.isAssignableFrom(clazz) && isConfigurationSection(cs.get(path))) { Class subClazz = getClassAtDepth(field.getGenericType(), depth + 1); if (ConfigObject.class.isAssignableFrom(subClazz) || Location.class.isAssignableFrom(subClazz) || Vector.class.isAssignableFrom(subClazz) || Map.class.isAssignableFrom(subClazz) || List.class.isAssignableFrom(subClazz) || subClazz.isEnum()) { return getList(field, cs.getConfigurationSection(path), path, depth); } else { return cs.get(path); } } else { return cs.get(path); } }
public <J extends JIRAObject<J>> void replaceMembersByIdentityMembers() { Class<?> klass = getClass(); while (klass != null) { for (Field field : klass.getDeclaredFields()) { if (JIRAObject.class.isAssignableFrom(field.getType())) { field.setAccessible(true); try { J object = (J) field.get(this); if (object != null) { field.set(this, object.getAsIdentityObject()); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (List.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType && ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0] instanceof Class && JIRAObject.class.isAssignableFrom( (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0])) { field.setAccessible(true); try { List<J> list = (List<J>) field.get(this); if (list != null) { List<J> newList = new ArrayList<J>(); for (J j : list) { newList.add(j.getAsIdentityObject()); } field.set(this, newList); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } klass = klass.getSuperclass(); } membersHaveBeenReplaced = true; }
@SuppressWarnings("unchecked") @Test public void FullySerializable() { Set<Class<?>> checked = new HashSet<Class<?>>(); checked.addAll( Arrays.asList( Collection.class, List.class, Set.class, Map.class, Object.class, String.class, Class.class)); Stack<Class<?>> classes = new Stack<Class<?>>(); classes.addAll( Arrays.<Class<?>>asList( NumberPath.class, NumberOperation.class, NumberTemplate.class, BeanPath.class, DefaultQueryMetadata.class)); while (!classes.isEmpty()) { Class<?> clazz = classes.pop(); checked.add(clazz); if (!Serializable.class.isAssignableFrom(clazz) && !clazz.isPrimitive()) { fail(clazz.getName() + " is not serializable"); } for (Field field : clazz.getDeclaredFields()) { if (Modifier.isTransient(field.getModifiers())) { continue; } Set<Class<?>> types = new HashSet<Class<?>>(3); types.add(field.getType()); if (field.getType().getSuperclass() != null) { types.add(field.getType().getSuperclass()); } if (field.getType().getComponentType() != null) { types.add(field.getType().getComponentType()); } if (Collection.class.isAssignableFrom(field.getType())) { types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 0)); } else if (Map.class.isAssignableFrom(field.getType())) { types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 0)); types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 1)); } types.removeAll(checked); classes.addAll(types); } } }
/** @return the generic type of the collection for this field, or null if not applicable. */ public Type findFieldGenericType() { if (m_method != null) { return null; } else { if (m_field.getGenericType() instanceof ParameterizedType) { ParameterizedType p = (ParameterizedType) m_field.getGenericType(); Type cls = p.getActualTypeArguments()[0]; if (cls instanceof Class) { return cls; } } } return null; }
/** * 一対多の関連を処理します。 * * @param propertyMeta プロパティメタデータ * @param field フィールド * @param entityMeta エンティティメタデータ * @param oneToMany 一対多関連 */ protected void doOneToMany( PropertyMeta propertyMeta, Field field, EntityMeta entityMeta, OneToMany oneToMany) { propertyMeta.setRelationshipType(RelationshipType.ONE_TO_MANY); if (!List.class.isAssignableFrom(field.getType())) { throw new OneToManyNotListRuntimeException(entityMeta.getName(), propertyMeta.getName()); } Class<?> relationshipClass = ReflectionUtil.getElementTypeOfList(field.getGenericType()); if (relationshipClass == null) { throw new OneToManyNotGenericsRuntimeException(entityMeta.getName(), propertyMeta.getName()); } if (relationshipClass.getAnnotation(Entity.class) == null) { throw new RelationshipNotEntityRuntimeException( entityMeta.getName(), propertyMeta.getName(), relationshipClass); } propertyMeta.setRelationshipClass(relationshipClass); String mappedBy = oneToMany.mappedBy(); if (!StringUtil.isEmpty(mappedBy)) { if (propertyMeta.getJoinColumnMetaList().size() > 0) { throw new BothMappedByAndJoinColumnRuntimeException( entityMeta.getName(), propertyMeta.getName()); } propertyMeta.setMappedBy(mappedBy); } else { throw new MappedByMandatoryRuntimeException(entityMeta.getName(), propertyMeta.getName()); } }
private static ParameterizedType getType(Field paramField) { paramField = paramField.getGenericType(); if ((paramField instanceof ParameterizedType)) { return (ParameterizedType) paramField; } return null; }
/** * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually * should go to struct. * * @param from * @param to * @param excludes * @return * @throws Exception */ public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception { Arrays.sort(excludes); for (Field f : from.fields()) { if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue; Object o = f.get(from); if (o == null) continue; Field tof = to.getField(f.getName()); if (tof != null) try { tof.set(to, Converter.cnv(tof.getGenericType(), o)); } catch (Exception e) { System.out.println( "Failed to convert " + f.getName() + " from " + from.getClass() + " to " + to.getClass() + " value " + o + " exception " + e); } } return to; }
private void setRelationProperty(Object instance, FieldRecord fieldRecord) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException, CannotCompileException { String fieldName = fieldRecord.getName(); String methodName = MemberUtil.getSetterName(fieldName); Class<?> clazz = instance.getClass().getClassLoader().loadClass(instance.getClass().getName()); Field field = FieldUtils.getField(clazz, fieldName, true); Class<?> parameterType = field.getType(); Object value = null; MotechDataService serviceForRelatedClass = null; TypeDto type = getType(fieldRecord); if (StringUtils.isNotEmpty(ObjectUtils.toString(fieldRecord.getValue()))) { if (type.equals(TypeDto.ONE_TO_MANY_RELATIONSHIP) || type.equals(TypeDto.MANY_TO_MANY_RELATIONSHIP)) { Class<?> genericType = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; serviceForRelatedClass = DataServiceHelper.getDataService(bundleContext, genericType.getName()); } else if (type.equals(TypeDto.MANY_TO_ONE_RELATIONSHIP) || type.equals(TypeDto.ONE_TO_ONE_RELATIONSHIP)) { serviceForRelatedClass = DataServiceHelper.getDataService(bundleContext, parameterType.getName()); } value = buildRelatedInstances(serviceForRelatedClass, parameterType, fieldRecord.getValue()); } Method method = MethodUtils.getAccessibleMethod(instance.getClass(), methodName, parameterType); invokeMethod(method, instance, value, methodName, fieldName); }
private static GenericType getFieldType( VariableMapping currentMapping, Class<?> startClass, String fieldname) { Type type = null; Field field = null; // e.g. BClass<String, Integer> bObject; { Class<?> ownerClass = startClass; findfield: while (true) { Field[] fields = ownerClass.getDeclaredFields(); for (Field f : fields) { if (f.getName().equals(fieldname)) { field = f; break findfield; } } // field not found so far // -> search superclass Type superType = ownerClass.getGenericSuperclass(); if (superType instanceof ParameterizedType) { ParameterizedType parameterizedSuperType = (ParameterizedType) superType; currentMapping = new VariableMapping(currentMapping, parameterizedSuperType); ownerClass = (Class<?>) parameterizedSuperType.getRawType(); } else if (superType instanceof Class<?>) { ownerClass = (Class<?>) superType; } else { throw new IllegalStateException(); } } } type = field.getGenericType(); // e.g. BClass<String, Integer> return getGenericType(currentMapping, type); }
public Type getGenericType() { if (m_method != null) { return m_method.getGenericParameterTypes()[0]; } else { return m_field.getGenericType(); } }
@SuppressWarnings("unchecked") private Object toValue(Object bean, Field field, XMLNode node) throws Exception { Class<?> type = field.getType(); field.setAccessible(true); Object current = field.get(bean); if (current != null) type = current.getClass(); if (Collection.class.isAssignableFrom(type)) { Type eleParamType = Object.class; ParameterizedType paramType = (ParameterizedType) field.getGenericType(); if (paramType.getActualTypeArguments().length > 0) { eleParamType = paramType.getActualTypeArguments()[0]; } Object[] array = (Object[]) toArrayValues((Class<?>) eleParamType, node); Collection collection = null; if (current != null && current instanceof Collection) { collection = (Collection) current; } else if (type.isInterface()) { collection = new ArrayList<Object>(); } else { collection = (Collection) type.newInstance(); } Collections.addAll(collection, array); return collection; } if (type.isArray()) return toArrayValues(type, node); return toValue(type, node); }
/** * Determine the type of the List,Set or Map. Not been set explicitly so determine this from * ParameterizedType. */ private Class<?> determineTargetType(Field field) { Type genType = field.getGenericType(); if (genType instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) genType; Type[] typeArgs = ptype.getActualTypeArguments(); if (typeArgs.length == 1) { // probably a Set or List if (typeArgs[0] instanceof Class<?>) { return (Class<?>) typeArgs[0]; } throw new RuntimeException("Unexpected Parameterised Type? " + typeArgs[0]); } if (typeArgs.length == 2) { // this is probably a Map if (typeArgs[1] instanceof ParameterizedType) { // not supporting ParameterizedType on Map. return null; } return (Class<?>) typeArgs[1]; } } // if targetType is null, then must be set in annotations return null; }
protected String getClassType(Method method, List<Class<?>> alsoRead) { Field field = getFieldForMethod(method); if (field == null) { return "n/a"; } if (List.class.isAssignableFrom(field.getType())) { Type generic = field.getGenericType(); if (listWithSingleGenericType(generic)) { Type genericType = ((ParameterizedType) generic).getActualTypeArguments()[0]; // if the generic type is not specified, we'll just return "list of T" if (!(genericType instanceof Class<?>)) { return "List of T"; } else { Class genericClass = (Class) genericType; if (!skipForInspection(genericClass)) { alsoRead.add(genericClass); } return "List of ".concat(genericClass.getSimpleName()); } } else { return "List"; } } else { if (!skipForInspection(method.getReturnType())) { alsoRead.add(method.getReturnType()); } return method.getReturnType().getSimpleName(); } }
/** Creates a {@link PluginPropertyField} based on the given field. */ private PluginPropertyField createPluginProperty(Field field, TypeToken<?> resolvingType) throws UnsupportedTypeException { TypeToken<?> fieldType = resolvingType.resolveType(field.getGenericType()); Class<?> rawType = fieldType.getRawType(); Name nameAnnotation = field.getAnnotation(Name.class); Description descAnnotation = field.getAnnotation(Description.class); String name = nameAnnotation == null ? field.getName() : nameAnnotation.value(); String description = descAnnotation == null ? "" : descAnnotation.value(); if (rawType.isPrimitive()) { return new PluginPropertyField(name, description, rawType.getName(), true); } rawType = Primitives.unwrap(rawType); if (!rawType.isPrimitive() && !String.class.equals(rawType)) { throw new UnsupportedTypeException("Only primitive and String types are supported"); } boolean required = true; for (Annotation annotation : field.getAnnotations()) { if (annotation.annotationType().getName().endsWith(".Nullable")) { required = false; break; } } return new PluginPropertyField( name, description, rawType.getSimpleName().toLowerCase(), required); }
@Test public void resolveSerializationBeanListOneFieldRequired() throws Exception { // given Field listField = getField("beanCollectionFieldRequired"); Type listType = listField.getGenericType(); // when SerializationInput input = new SerializationInputResolver() .resolveInputInformation(listField.getAnnotation(Bind.class)); PropertySerialization listSerialization = serializationResolver.resolveSerialization(listType, input); PropertySerialization listElementSerialization = listSerialization.getPropertySerialization( PropertySerialization.CONTAINER_ELEMENT_PROPERTY_NAME); PropertySerialization beanElementSerialization = listElementSerialization.getPropertySerialization("simpleField"); // then assertNotNull(listSerialization); assertNotNull(listElementSerialization); assertNotNull(beanElementSerialization); assertEquals( IntegerValueSerializer.class, beanElementSerialization.getValueSerializer().getClass()); assertEquals(VerySimpleMockBean.class, listElementSerialization.getPropertyClass()); assertEquals(int.class, beanElementSerialization.getPropertyClass()); assertTrue(beanElementSerialization.getConstraints().isRequired()); }
/** * フィールドの型を表現する{@link ParameterizedClassDesc}を作成して返します。 * * @param field フィールド。{@literal null}であってはいけません * @param map パラメータ化された型が持つ型変数をキー、型引数を値とする{@link Map}。{@literal null} であってはいけません * @return フィールドの型を表現する{@link ParameterizedClassDesc} */ public static ParameterizedClassDesc createParameterizedClassDesc( final Field field, final Map<TypeVariable<?>, Type> map) { assertArgumentNotNull("field", field); assertArgumentNotNull("map", map); return createParameterizedClassDesc(field.getGenericType(), map); }
@Override @SuppressWarnings("unchecked") protected void configure() { // Bind mock controllet to this instance, to automatically replay/verify all mocks created by // runner. bind(MockController.class).toInstance(this); // map field values by type for (Field field : fields.keySet()) { TypeLiteral literal = TypeLiteral.get(field.getGenericType()); AnnotatedBindingBuilder builder = bind(literal); // Check field annotations. Annotation[] fieldAnnotations = field.getAnnotations(); for (Annotation annotation : fieldAnnotations) { Class<? extends Annotation> annotationType = annotation.annotationType(); if ( /* annotationType.isAnnotationPresent(Qualifier.class)|| */ annotationType .isAnnotationPresent(BindingAnnotation.class)) { builder.annotatedWith(annotation); } if (annotationType.isAnnotationPresent(ScopeAnnotation.class)) { builder.in(annotationType); } } Binding binding = fields.get(field); if (null != binding.getValue()) { builder.toInstance(binding.getValue()); } else if (null != binding.getImplementation()) { builder.to(binding.getImplementation()); } else if (null != binding.getProvider()) { builder.toProvider(binding.getProvider()); } } }
public static Class getCollectionGenericType(Field field) throws Exception { // Field field = bean.getClass().getDeclaredField(fName); String type = field.getGenericType().toString(); String paraType = type.substring(type.indexOf('<') + 1, type.indexOf('>')); debug("paraType=" + paraType); Class res = Class.forName(paraType); return res; }
private static void processListField(Object object, Field field, Node node, Node parentNode) throws IllegalArgumentException, IllegalAccessException, InstantiationException { ParameterizedType genericType = (ParameterizedType) field.getGenericType(); Class<?> childrenType = (Class<?>) genericType.getActualTypeArguments()[0]; field.set(object, getList(node, childrenType, parentNode)); }
/** * 获取域的泛型类型,如果不带泛型返回null * * @param f * @return */ public static Class<?> getGenericType(Field f) { Type type = f.getGenericType(); if (type instanceof ParameterizedType) { type = ((ParameterizedType) type).getActualTypeArguments()[0]; if (type instanceof Class<?>) return (Class<?>) type; } else if (type instanceof Class<?>) return (Class<?>) type; return null; }
/** * Returns the resolved generic type of {@code field}. * * @param field a field defined by this or any superclass. * @since 2.0 */ public TypeLiteral<?> getFieldType(Field field) { Assert.checkArgument( field.getDeclaringClass().isAssignableFrom(rawType), "%s is not defined by a supertype of %s", field, type); return resolve(field.getGenericType()); }
/** * Returns the generic type information of an attribute. * * @param field the field representation of the attribute. * @return an array of types that are used to parameterize the attribute. */ public static Class<?>[] getGenericTypes(Field field) { Type genericFieldType = field.getGenericType(); if (!(genericFieldType instanceof ParameterizedType)) return null; // type is not generic ParameterizedType pType = (ParameterizedType) genericFieldType; Type[] args = pType.getActualTypeArguments(); Class<?>[] types = new Class[args.length]; System.arraycopy(args, 0, types, 0, args.length); return types; }
@Test public void get_generic_type_of_a_field() throws Exception { Field field = Dummy.class.getDeclaredField("stringListField"); ParameterizedType type = (ParameterizedType) field.getGenericType(); assertEquals(List.class, type.getRawType()); assertArrayEquals(new Type[] {String.class}, type.getActualTypeArguments()); assertEquals(null, type.getOwnerType()); }
private <T extends PageObject> Class<T> getPageObjectClassFromListField( T pageInstance, Field listField) { ParameterizedType genericType = (ParameterizedType) listField.getGenericType(); Class<T> genericTypeClass = (Class<T>) genericType.getActualTypeArguments()[0]; if (!PageObject.class.isAssignableFrom(genericTypeClass)) { throw exception(pageInstance).unsupportedFieldClass(listField, genericTypeClass); } return genericTypeClass; }
private void buildQuery(Field field, Class<?> c) { Class<?> type = field.getType(); Filter filter = field.getAnnotation(Filter.class); Owned related = field.getAnnotation(Owned.class); if (filter == null && related == null) { throw new SienaException( "Found Query<T> field without @Filter or @Owned annotation at " + c.getName() + "." + field.getName()); } ParameterizedType pt = (ParameterizedType) field.getGenericType(); Class<?> cl = (Class<?>) pt.getActualTypeArguments()[0]; if (filter != null) { try { Map<FieldMapKeys, Object> fieldMap = new HashMap<FieldMapKeys, Object>(); fieldMap.put(FieldMapKeys.CLASS, cl); fieldMap.put(FieldMapKeys.FILTER, filter.value()); queryFieldMap.put(field, fieldMap); ownedFields.add(field); hasOwnedFields = true; } catch (Exception e) { throw new SienaException(e); } } else if (related != null) { String as = related.mappedBy(); // if related.as not specified, tries to find the first field with this type if ("".equals(as) || as == null) { ClassInfo fieldInfo = ClassInfo.getClassInfo(cl); Field f = fieldInfo.getFirstFieldFromType(clazz); if (f == null) { throw new SienaException( "@Owned without 'as' attribute and no field of type " + clazz.getName() + "found in class " + type.getName()); } as = ClassInfo.getSimplestColumnName(f); } try { Map<FieldMapKeys, Object> fieldMap = new HashMap<FieldMapKeys, Object>(); fieldMap.put(FieldMapKeys.CLASS, cl); fieldMap.put(FieldMapKeys.FILTER, as); queryFieldMap.put(field, fieldMap); ownedFields.add(field); hasOwnedFields = true; } catch (Exception e) { throw new SienaException(e); } } allExtendedFields.add(field); }
@Test public void testGenericTypes() throws Exception { assertThat( describe(genericField).getType(), is(GenericTypeDescription.Sort.describe(genericField.getGenericType()))); assertThat( describe(genericField).getType().asErasure(), is((TypeDescription) new TypeDescription.ForLoadedType(genericField.getType()))); }
private static SwaggerContainerType getContainerType(SwaggerModel models, Field field) { Class<?> type = getContainerType(field.getGenericType()); String refType = Object.class.getName(); if (type != null) { refType = convertToSwaggerType(models, type).dataType; } return new SwaggerContainerType(refType); }
public Object createNewObject(Field field) throws Exception { Type type = field.getGenericType(); if (type instanceof ParameterizedType) { ParameterizedType pT = (ParameterizedType) type; Type objectType = pT.getActualTypeArguments()[0]; Class objectClass = (Class) objectType; return objectClass.newInstance(); } return null; }