List of usage examples for java.lang.reflect Field getGenericType
public Type getGenericType()
From source file:org.spout.api.util.config.annotated.AnnotatedObjectConfiguration.java
@Override public void save(ConfigurationNodeSource source) throws ConfigurationException { for (Entry<Object, Set<Member>> entry : objectMembers.entrySet()) { final Object object = entry.getKey(); final String[] objectPath = objectPaths.get(object); final Set<Method> methods = new HashSet<Method>(); for (Member member : entry.getValue()) { if (member instanceof Method) { final Method method = (Method) member; if (method.isAnnotationPresent(Save.class)) { methods.add(method); }//from w w w. j a v a 2s . c o m continue; } final Field field = (Field) member; field.setAccessible(true); String[] fieldPath = field.getAnnotation(Setting.class).value(); if (fieldPath.length == 0) { fieldPath = new String[] { field.getName() }; } final ConfigurationNode fieldNode = source.getNode(ArrayUtils.addAll(objectPath, fieldPath)); try { fieldNode.setValue(field.getGenericType(), field.get(object)); } catch (IllegalAccessException ex) { throw new ConfigurationException(ex); } } invokeMethods(methods, object, source.getNode(objectPath)); } }
From source file:org.spout.api.util.config.annotated.AnnotatedObjectConfiguration.java
@Override public void load(ConfigurationNodeSource source) throws ConfigurationException { for (Entry<Object, Set<Member>> entry : objectMembers.entrySet()) { final Object object = entry.getKey(); final String[] objectPath = objectPaths.get(object); final Set<Method> methods = new HashSet<Method>(); for (Member member : entry.getValue()) { if (member instanceof Method) { final Method method = (Method) member; if (method.isAnnotationPresent(Load.class)) { methods.add(method); }/*from w ww. ja v a 2 s. co m*/ continue; } final Field field = (Field) member; field.setAccessible(true); String[] fieldPath = field.getAnnotation(Setting.class).value(); if (fieldPath.length == 0) { fieldPath = new String[] { field.getName() }; } final ConfigurationNode fieldNode = source.getNode(ArrayUtils.addAll(objectPath, fieldPath)); final Object value = fieldNode.getTypedValue(field.getGenericType()); try { if (value != null) { field.set(object, value); } else { fieldNode.setValue(field.getGenericType(), field.get(object)); } } catch (IllegalAccessException ex) { throw new ConfigurationException(ex); } } invokeMethods(methods, object, source.getNode(objectPath)); } }
From source file:richtercloud.reflection.form.builder.jpa.fieldhandler.JPAMappingFieldHandler.java
@Override protected Pair<JComponent, ComponentHandler<?>> handle0(Field field, Object instance, final FieldUpdateListener updateListener, JPAReflectionFormBuilder reflectionFormBuilder) throws IllegalArgumentException, IllegalAccessException, FieldHandlingException, InvocationTargetException, NoSuchMethodException, InstantiationException { if (field == null) { throw new IllegalArgumentException("fieldClass mustn't be null"); }// ww w.ja va 2 s . co m Type fieldType = field.getGenericType(); Object fieldValue = field.get(instance); String fieldName = field.getName(); Class<?> fieldDeclaringClass = field.getDeclaringClass(); if (field.getAnnotation(Id.class) != null) { if (!(fieldType instanceof Class)) { throw new IllegalArgumentException("@Id annotated field has to be a class"); } Class<?> fieldTypeClass = (Class<?>) fieldType; if (fieldTypeClass.equals(Long.class)) { Long fieldValueCast = (Long) field.get(instance); NumberPanel<Long> retValue; if (fieldType.equals(Long.class)) { retValue = new LongIdPanel(this.idGenerator, instance, fieldValueCast, //initialValue messageHandler, fieldRetriever); } else { throw new IllegalArgumentException( String.format("field type %s is not supported", fieldValue.getClass())); } retValue.addUpdateListener(new NumberPanelUpdateListener<Long>() { @Override public void onUpdate(NumberPanelUpdateEvent<Long> event) { updateListener.onUpdate(new FieldUpdateEvent<>(event.getNewValue())); } }); return new ImmutablePair<JComponent, ComponentHandler<?>>(retValue, LONG_ID_PANEL_COMPONENT_RESETTER); } else { throw new IllegalArgumentException( String.format("@Id annotated field type %s not supported", field.getGenericType())); } } if (field.getAnnotation(ElementCollection.class) != null) { //can't be handled differently because otherwise a QueryPanel would //be tried to be used and IllegalArgumentException thrown at //initialization if (fieldValue != null && !(fieldValue instanceof List)) { throw new IllegalArgumentException("field values isn't an instance of List"); } Pair<JComponent, ComponentHandler<?>> retValue = this.elementCollectionTypeHandler.handle( field.getGenericType(), (List<Object>) fieldValue, fieldName, fieldDeclaringClass, updateListener, reflectionFormBuilder); return retValue; } if (field.getAnnotation(OneToMany.class) != null || field.getAnnotation(ManyToMany.class) != null) { Pair<JComponent, ComponentHandler<?>> retValue = this.toManyTypeHandler.handle(field.getGenericType(), (List<Object>) fieldValue, fieldName, fieldDeclaringClass, updateListener, reflectionFormBuilder); return retValue; } if (field.getAnnotation(OneToOne.class) != null || field.getAnnotation(ManyToOne.class) != null) { Pair<JComponent, ComponentHandler<?>> retValue = this.toOneTypeHandler.handle(field.getGenericType(), fieldValue, fieldName, fieldDeclaringClass, updateListener, reflectionFormBuilder); return retValue; } if (field.getType() instanceof Class) { Class<?> fieldTypeClass = field.getType(); if (fieldTypeClass.getAnnotation(Embeddable.class) != null) { FieldHandler fieldHandler = embeddableMapping.get(fieldType); JComponent retValue = fieldHandler.handle(field, instance, updateListener, reflectionFormBuilder); return new ImmutablePair<JComponent, ComponentHandler<?>>(retValue, fieldHandler); } } return super.handle0(field, instance, updateListener, reflectionFormBuilder); }
From source file:org.openmrs.module.sync.SyncUtil.java
public static Object valForField(String fieldName, String fieldVal, ArrayList<Field> allFields, Node n) { Object o = null;// www. jav a 2 s . co m // the String value on the node specifying the "type" String nodeDefinedClassName = null; if (n != null) { Node tmpNode = n.getAttributes().getNamedItem("type"); if (tmpNode != null) nodeDefinedClassName = tmpNode.getTextContent(); } // TODO: Speed up sync by passing in a Map of String fieldNames instead of list of Fields ? // TODO: Speed up sync by returning after "o" is first set? Or are we doing "last field wins" ? for (Field f : allFields) { //log.debug("field is " + f.getName()); if (f.getName().equals(fieldName)) { Class classType = null; String className = f.getGenericType().toString(); // the string class name for the actual field // if its a collection, set, list, etc if (ParameterizedType.class.isAssignableFrom(f.getGenericType().getClass())) { ParameterizedType pType = (ParameterizedType) f.getGenericType(); classType = (Class) pType.getRawType(); // can this be anything but Class at this point?! } if (className.startsWith("class ")) { className = className.substring("class ".length()); classType = (Class) f.getGenericType(); } else { log.trace("Abnormal className for " + f.getGenericType()); } if (classType == null) { if ("int".equals(className)) { return new Integer(fieldVal); } else if ("long".equals(className)) { return new Long(fieldVal); } else if ("double".equals(className)) { return new Double(fieldVal); } else if ("float".equals(className)) { return new Float(fieldVal); } else if ("boolean".equals(className)) { return new Boolean(fieldVal); } else if ("byte".equals(className)) { return new Byte(fieldVal); } else if ("short".equals(className)) { return new Short(fieldVal); } } // we have to explicitly create a new value object here because all we have is a string - won't know how to convert if (OpenmrsObject.class.isAssignableFrom(classType)) { o = getOpenmrsObj(className, fieldVal); } else if ("java.lang.Integer".equals(className) && !("integer".equals(nodeDefinedClassName) || "java.lang.Integer".equals(nodeDefinedClassName))) { // if we're dealing with a field like PersonAttributeType.foreignKey, the actual value was changed from // an integer to a uuid by the HibernateSyncInterceptor. The nodeDefinedClassName is the node.type which is the // actual classname as defined by the PersonAttributeType.format. However, the field.getClassName is // still an integer because thats what the db stores. we need to convert the uuid to the pk integer and return it OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal); o = obj.getId(); } else if ("java.lang.String".equals(className) && !("text".equals(nodeDefinedClassName) || "string".equals(nodeDefinedClassName) || "java.lang.String".equals(nodeDefinedClassName) || "integer".equals(nodeDefinedClassName) || "java.lang.Integer".equals(nodeDefinedClassName) || fieldVal.isEmpty())) { // if we're dealing with a field like PersonAttribute.value, the actual value was changed from // a string to a uuid by the HibernateSyncInterceptor. The nodeDefinedClassName is the node.type which is the // actual classname as defined by the PersonAttributeType.format. However, the field.getClassName is // still String because thats what the db stores. we need to convert the uuid to the pk integer/string and return it OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal); if (obj == null) { if (StringUtils.hasText(fieldVal)) { // If we make it here, and we are dealing with person attribute values, then just return the string value as-is if (PersonAttribute.class.isAssignableFrom(f.getDeclaringClass()) && "value".equals(f.getName())) { o = fieldVal; } else { // throw a warning if we're having trouble converting what should be a valid value log.error("Unable to convert value '" + fieldVal + "' into a " + nodeDefinedClassName); throw new SyncException("Unable to convert value '" + fieldVal + "' into a " + nodeDefinedClassName); } } else { // if fieldVal is empty, just save an empty string here too o = ""; } } else { o = obj.getId().toString(); // call toString so the class types match when looking up the setter } } else if (Collection.class.isAssignableFrom(classType)) { // this is a collection of items. this is intentionally not in the convertStringToObject method Collection tmpCollection = null; if (Set.class.isAssignableFrom(classType)) tmpCollection = new LinkedHashSet(); else tmpCollection = new Vector(); // get the type of class held in the collection String collectionTypeClassName = null; java.lang.reflect.Type collectionType = ((java.lang.reflect.ParameterizedType) f .getGenericType()).getActualTypeArguments()[0]; if (collectionType.toString().startsWith("class ")) collectionTypeClassName = collectionType.toString().substring("class ".length()); // get the type of class defined in the text node // if it is different, we could be dealing with something like Cohort.memberIds // node type comes through as java.util.Set<classname> String nodeDefinedCollectionType = null; int indexOfLT = nodeDefinedClassName.indexOf("<"); if (indexOfLT > 0) nodeDefinedCollectionType = nodeDefinedClassName.substring(indexOfLT + 1, nodeDefinedClassName.length() - 1); // change the string to just a comma delimited list fieldVal = fieldVal.replaceFirst("\\[", "").replaceFirst("\\]", ""); for (String eachFieldVal : fieldVal.split(",")) { eachFieldVal = eachFieldVal.trim(); // take out whitespace if (!StringUtils.hasText(eachFieldVal)) continue; // try to convert to a simple object Object tmpObject = convertStringToObject(eachFieldVal, (Class) collectionType); // convert to an openmrs object if (tmpObject == null && nodeDefinedCollectionType != null) tmpObject = getOpenmrsObj(nodeDefinedCollectionType, eachFieldVal).getId(); if (tmpObject == null) log.error("Unable to convert: " + eachFieldVal + " to a " + collectionTypeClassName); else tmpCollection.add(tmpObject); } o = tmpCollection; } else if (Map.class.isAssignableFrom(classType) || Properties.class.isAssignableFrom(classType)) { Object tmpMap = SyncUtil.getNormalizer(classType).fromString(classType, fieldVal); //if we were able to convert and got anything at all back, assign it if (tmpMap != null) { o = tmpMap; } } else if ((o = convertStringToObject(fieldVal, classType)) != null) { log.trace("Converted " + fieldVal + " into " + classType.getName()); } else { log.debug("Don't know how to deserialize class: " + className); } } } if (o == null) log.debug("Never found a property named: " + fieldName + " for this class"); return o; }
From source file:org.optaplanner.core.impl.domain.solution.cloner.FieldAccessingSolutionCloner.java
protected boolean isFieldAnEntityOrSolution(Field field, Class fieldInstanceClass) { Class<?> type = field.getType(); if (isClassDeepCloned(type)) { return true; }/*from w ww .ja va 2 s . co m*/ if (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)) { if (isTypeArgumentDeepCloned(field.getGenericType())) { return true; } } return false; }
From source file:org.debux.webmotion.server.handler.ExecutorParametersConvertorHandler.java
protected Object convert(ParameterTree parameterTree, Class<?> type, Type genericType) throws Exception { Object result = null;//from w w w. j a v a 2s.co m if (parameterTree == null) { return null; } if (genericType == null) { genericType = type.getGenericSuperclass(); } Map<String, List<ParameterTree>> parameterArray = parameterTree.getArray(); Map<String, ParameterTree> parameterObject = parameterTree.getObject(); Object value = parameterTree.getValue(); Converter lookup = converter.lookup(type); if (lookup != null) { // converter found, use it result = lookup.convert(type, value); return result; } // Manage enums if (type.isEnum()) { Object name = value == null ? null : ((Object[]) value)[0]; if (name != null) { result = Enum.valueOf((Class<? extends Enum>) type, name.toString()); } // Manage collection } else if (Collection.class.isAssignableFrom(type)) { Collection instance; if (type.isInterface()) { if (List.class.isAssignableFrom(type)) { instance = new ArrayList(); } else if (Set.class.isAssignableFrom(type)) { instance = new HashSet(); } else if (SortedSet.class.isAssignableFrom(type)) { instance = new TreeSet(); } else { instance = new ArrayList(); } } else { instance = (Collection) type.newInstance(); } Class convertType = String.class; if (genericType != null && genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; convertType = (Class) parameterizedType.getActualTypeArguments()[0]; } if (parameterObject != null) { for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) { ParameterTree object = entry.getValue(); Object converted = convert(object, convertType, null); instance.add(converted); } } else { Object[] tab = (Object[]) value; for (Object object : tab) { Object converted = converter.convert(object, convertType); instance.add(converted); } } result = instance; // Manage map } else if (Map.class.isAssignableFrom(type)) { Map instance; if (type.isInterface()) { if (SortedMap.class.isAssignableFrom(type)) { instance = new TreeMap(); } else { instance = new HashMap(); } } else { instance = (Map) type.newInstance(); } Class convertKeyType = String.class; Class convertValueType = String.class; if (genericType != null && genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; convertKeyType = (Class) parameterizedType.getActualTypeArguments()[0]; convertValueType = (Class) parameterizedType.getActualTypeArguments()[1]; } for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) { String mapKey = entry.getKey(); ParameterTree mapValue = entry.getValue(); Object convertedKey = converter.convert(mapKey, convertKeyType); Object convertedValue = convert(mapValue, convertValueType, null); instance.put(convertedKey, convertedValue); } result = instance; // Manage simple object } else if (type.isArray()) { Class<?> componentType = type.getComponentType(); if (parameterObject != null) { Object[] tabConverted = (Object[]) Array.newInstance(componentType, parameterObject.size()); result = tabConverted; int index = 0; for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) { ParameterTree object = entry.getValue(); Object objectConverted = convert(object, componentType, null); tabConverted[index] = objectConverted; index++; } } else { Object[] tab = (Object[]) value; Object[] tabConverted = (Object[]) Array.newInstance(componentType, tab.length); result = tabConverted; for (int index = 0; index < tab.length; index++) { Object object = tab[index]; Object objectConverted = converter.convert(object, componentType); tabConverted[index] = objectConverted; } } } else if (value instanceof UploadFile) { if (File.class.isAssignableFrom(type)) { UploadFile uploadFile = (UploadFile) value; result = uploadFile.getFile(); } else { result = value; } // Manage simple object } else { Object instance = type.newInstance(); boolean one = false; if (parameterObject != null) { for (Map.Entry<String, ParameterTree> attribut : parameterObject.entrySet()) { String attributeName = attribut.getKey(); ParameterTree attributeValue = attribut.getValue(); boolean writeable = propertyUtils.isWriteable(instance, attributeName); if (writeable) { one = true; Field field = FieldUtils.getField(type, attributeName, true); Class<?> attributeType = field.getType(); genericType = field.getGenericType(); Object attributeConverted = convert(attributeValue, attributeType, genericType); beanUtil.setProperty(instance, attributeName, attributeConverted); } } } if (parameterArray != null) { for (Map.Entry<String, List<ParameterTree>> entry : parameterArray.entrySet()) { String attributeName = entry.getKey(); List<ParameterTree> attributeValues = entry.getValue(); boolean writeable = propertyUtils.isWriteable(instance, attributeName); if (writeable) { one = true; Field field = FieldUtils.getField(type, attributeName, true); Class<?> attributeType = field.getType(); genericType = field.getGenericType(); Object attributeConverted = convert(attributeValues, attributeType, genericType); beanUtil.setProperty(instance, attributeName, attributeConverted); } } } if (one) { result = instance; } else { result = null; } } return result; }
From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java
protected void fillField(Field f, Object o, Map<String, Type> map, ITestContext iTestContext) { f.setAccessible(true);// ww w . ja v a 2s. c om try { Type fType = ITestTypeUtil.getTypeProxy(f.getGenericType(), map); iTestContext.enter(o, f.getName()); ITestParamState fITestState = iTestContext.getCurrentParam(); String fITestValue = fITestState == null ? null : fITestState.getValue(); Object oRes; // if ( fITestState != null && null != fITestState.getAttribute(ITestConstants.REFERENCE_ATTRIBUTE) ) { // oRes = iTestContext.findGeneratedObject(fITestState.getAttribute(ITestConstants.REFERENCE_ATTRIBUTE)); // } else if (null == fITestState && iTestContext.isStaticAssignmentRegistered(o.getClass(), f.getName())) { iTestContext.registerAssignment(o.getClass(), f.getName()); oRes = null;//TODO: implement it } else if (null == fITestState && f.isAnnotationPresent(ITestFieldAssignment.class)) { iTestContext.registerAssignment(f.getAnnotation(ITestFieldAssignment.class).value()); oRes = null;//TODO: implement it } else if (null == fITestState && f.isAnnotationPresent(ITestFieldClass.class)) { iTestContext.setEmptyParam(); oRes = generateRandom((Type) f.getAnnotation(ITestFieldClass.class).value(), map, iTestContext); f.set(o, oRes); // } else if (null != fITestValue) { // if (fITestValue.startsWith(":")) { // // TODO: register assignment // oRes = null;//TODO: implement it // } else { // oRes = iTestConfig.getITestValueConverter().convert(f.getType(), fITestValue); // f.set(o, oRes); // } } else { oRes = generateRandom(fType, map, iTestContext); f.set(o, oRes); } f.set(o, oRes); iTestContext.leave(oRes); } catch (ITestException e) { e.addPrefix(f.getName()); throw e; } catch (IllegalArgumentException e) { throw new ITestIllegalArgumentException(e); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.haulmont.cuba.core.sys.persistence.MappingFileCreator.java
private List<Attr> processClass(Class aClass, Map<Class, Class> extendedClasses) { List<Attr> list = new ArrayList<>(); for (Field field : aClass.getDeclaredFields()) { Attr.Type type = getAttrType(field); if (type != null) { Class<?> fieldType = field.getType(); Class extClass = null; if (Collection.class.isAssignableFrom(fieldType)) { Type genericType = field.getGenericType(); if (genericType instanceof ParameterizedType) { Type[] typeArguments = ((ParameterizedType) genericType).getActualTypeArguments(); if (typeArguments.length == 1) { extClass = extendedClasses.get((Class) typeArguments[0]); }/*from w w w .j a v a 2 s . co m*/ } } else { extClass = extendedClasses.get(fieldType); } if (extClass != null) { Attr attr = new Attr(type, field, extClass.getName()); list.add(attr); } } } return list; }
From source file:com.netflix.governator.lifecycle.ConfigurationProcessor.java
void assignConfiguration(Object obj, Field field, Map<String, String> contextOverrides) throws Exception { Configuration configuration = field.getAnnotation(Configuration.class); String configurationName = configuration.value(); ConfigurationKey key = new ConfigurationKey(configurationName, KeyParser.parse(configurationName, contextOverrides)); Object value = null;/*from ww w . j av a 2 s. c om*/ boolean has = configurationProvider.has(key); if (has) { try { if (Supplier.class.isAssignableFrom(field.getType())) { ParameterizedType type = (ParameterizedType) field.getGenericType(); Class<?> actualType = (Class<?>) type.getActualTypeArguments()[0]; Supplier<?> current = (Supplier<?>) field.get(obj); value = getConfigurationSupplier(field, key, actualType, current); if (value == null) { log.error("Field type not supported: " + actualType + " (" + field.getName() + ")"); field = null; } } else { Supplier<?> supplier = getConfigurationSupplier(field, key, field.getType(), Suppliers.ofInstance(field.get(obj))); if (supplier == null) { log.error("Field type not supported: " + field.getType() + " (" + field.getName() + ")"); field = null; } else { value = supplier.get(); } } } catch (IllegalArgumentException e) { ignoreTypeMismtachIfConfigured(configuration, configurationName, e); field = null; } catch (ConversionException e) { ignoreTypeMismtachIfConfigured(configuration, configurationName, e); field = null; } } if (field != null) { String defaultValue; if (Supplier.class.isAssignableFrom(field.getType())) { defaultValue = String.valueOf(((Supplier<?>) field.get(obj)).get()); } else { defaultValue = String.valueOf(field.get(obj)); } String documentationValue; if (has) { field.set(obj, value); documentationValue = String.valueOf(value); if (Supplier.class.isAssignableFrom(field.getType())) { documentationValue = String.valueOf(((Supplier<?>) value).get()); } else { documentationValue = String.valueOf(documentationValue); } } else { documentationValue = ""; } configurationDocumentation.registerConfiguration(field, configurationName, has, defaultValue, documentationValue, configuration.documentation()); } }
From source file:com.fluidops.iwb.ui.configuration.ConfigurationFormBase.java
/** * Retrieves all {@link FormElementConfig}s for the given configuration class. * //w ww . ja va2 s . co m * This is * a) a configuration for each {@link Field} that is annotated with {@link ParameterConfigDoc} * * The elements are sorted according to the rules as defined in {@link #getConfigFieldsSorted(Class)}. * * Note that deprecated fields are only rendered if there exists a preset value for it. * * This method also applies the {@link HiddenIfUnset} annotation concept. * * @param configClass * @return */ List<FormElementConfig> getFormElementConfigurations(Class<?> configClass) { if (configClass.equals(String.class)) return Lists.newArrayList(new FormElementConfig("", FormElementConfig.toParameterConfigDoc("", Type.SIMPLE, true), String.class, presetValues)); List<FormElementConfig> res = Lists.newArrayList(); for (Field f : ConfigurationFormUtil.getConfigFieldsSorted(configClass)) { if (!keepFieldAsFormElement(f)) continue; String fieldName = f.getName(); Class<?> nestedConfigClass = f.getType(); if (List.class.isAssignableFrom(nestedConfigClass)) { // use the list generic type nestedConfigClass = (Class<?>) ((ParameterizedType) f.getGenericType()).getActualTypeArguments()[0]; } Operator formElementDefaultValue = getChildOperator(presetValues, fieldName); FormElementConfig fCfg = new FormElementConfig(fieldName, f.getAnnotation(ParameterConfigDoc.class), nestedConfigClass, formElementDefaultValue); // show deprecated fields only if they have value (bug 10999) if (f.getAnnotation(Deprecated.class) != null) { if (!formElementDefaultValue.isNoop()) fCfg.setDeprecated(true); else continue; } // allow hidden elements which are only shown if a value is set if (f.getAnnotation(HiddenIfUnset.class) != null) { if (formElementDefaultValue.isNoop()) continue; } // remember the annotations in the configuration (for later use) fCfg.addAnnotations(f.getAnnotations()); res.add(fCfg); } return res; }