List of usage examples for java.lang.reflect Field getGenericType
public Type getGenericType()
From source file:org.datacleaner.monitor.server.controllers.ComponentControllerV1.java
static void setPropertyType(ComponentDescriptor<?> descriptor, ConfiguredPropertyDescriptor propertyDescriptor, ComponentList.PropertyInfo propInfo) { // TODO: avoid instanceof by extending the basic ComponentDescriptor // interface (maybe add getter for property "Type" in addition to // "Class" ? ) SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); if (propertyDescriptor instanceof AbstractPropertyDescriptor) { Field f = ((AbstractPropertyDescriptor) propertyDescriptor).getField(); Type t = f.getGenericType(); if (t instanceof Class) { propInfo.setClassDetails(((Class<?>) t).getCanonicalName()); } else {//from ww w. j a va 2 s .co m propInfo.setClassDetails(f.getGenericType().toString()); } if (!propertyDescriptor.isInputColumn()) { try { ComponentHandler.mapper.acceptJsonFormatVisitor( ComponentHandler.mapper.constructType(f.getGenericType()), visitor); } catch (JsonMappingException e) { throw new RuntimeException(e); } } } else { propInfo.setClassDetails(propertyDescriptor.getType().getCanonicalName()); if (!propertyDescriptor.isInputColumn()) { try { ComponentHandler.mapper.acceptJsonFormatVisitor( ComponentHandler.mapper.constructType(propertyDescriptor.getType()), visitor); } catch (JsonMappingException e) { throw new RuntimeException(e); } } } propInfo.setClassName(propertyDescriptor.getType().getName()); if (!propertyDescriptor.isInputColumn()) { propInfo.setSchema(visitor.finalSchema()); } }
From source file:tech.sirwellington.alchemy.generator.ObjectGenerators.java
private static AlchemyGenerator<?> determineGeneratorForMapField(Field mapField, Class<?> mapType, Map<Class<?>, AlchemyGenerator<?>> generatorMappings) { ParameterizedType parameterizedType = (ParameterizedType) mapField.getGenericType(); Class<?> keyType = (Class<?>) parameterizedType.getActualTypeArguments()[0]; Class<?> valueType = (Class<?>) parameterizedType.getActualTypeArguments()[1]; AlchemyGenerator<?> keyGenerator = generatorMappings.getOrDefault(keyType, determineGeneratorFor(keyType, mapField, generatorMappings)); AlchemyGenerator<?> valueGenerator = generatorMappings.getOrDefault(valueType, determineGeneratorFor(valueType, mapField, generatorMappings)); Map<Object, Object> map = new HashMap<>(); int size = one(integers(10, 100)); for (int i = 0; i < size; ++i) { map.put(keyGenerator.get(), valueGenerator.get()); }//from w w w.j ava 2 s. c o m return () -> map; }
From source file:com.jedi.oracle.OracleTypeUtils.java
private static void findCustomTypesRecursive(List<Field> fields, Map<String, Class<?>> map) { for (Field field : fields) { Class fieldType = field.getType(); if (List.class.isAssignableFrom(fieldType)) { ParameterizedType listType = (ParameterizedType) field.getGenericType(); fieldType = (Class<?>) listType.getActualTypeArguments()[0]; }//from w w w.j av a 2 s . co m if (fieldType.isAnnotationPresent(CustomTypeMapping.class)) { CustomTypeMapping mapping = (CustomTypeMapping) fieldType.getAnnotation(CustomTypeMapping.class); map.put(mapping.name(), fieldType); List<Field> oracleObjectFields = FieldUtils.getFieldsListWithAnnotation(fieldType, OracleObjectMapping.class); if (oracleObjectFields != null && !oracleObjectFields.isEmpty()) { findCustomTypesRecursive(oracleObjectFields, map); } } } }
From source file:streamflow.model.generator.RandomGenerator.java
public static <T, V, W> T randomObject(Class<T> objectClass, Class<V> typeClass1, Class<W> typeClass2) { T object = null;// www .ja v a 2s .c o m try { if (boolean.class.isAssignableFrom(objectClass) || Boolean.class.isAssignableFrom(objectClass)) { object = (T) randomBoolean(); } else if (byte.class.isAssignableFrom(objectClass) || Byte.class.isAssignableFrom(objectClass)) { object = (T) randomByte(); } else if (char.class.isAssignableFrom(objectClass) || Character.class.isAssignableFrom(objectClass)) { object = (T) randomChar(); } else if (short.class.isAssignableFrom(objectClass) || Short.class.isAssignableFrom(objectClass)) { object = (T) randomShort(); } else if (int.class.isAssignableFrom(objectClass) || Integer.class.isAssignableFrom(objectClass)) { object = (T) randomInt(); } else if (long.class.isAssignableFrom(objectClass) || Long.class.isAssignableFrom(objectClass)) { object = (T) randomLong(); } else if (float.class.isAssignableFrom(objectClass) || Float.class.isAssignableFrom(objectClass)) { object = (T) randomFloat(); } else if (double.class.isAssignableFrom(objectClass) || Double.class.isAssignableFrom(objectClass)) { object = (T) randomDouble(); } else if (String.class.isAssignableFrom(objectClass)) { object = (T) randomString(); } else if (Date.class.isAssignableFrom(objectClass)) { object = (T) randomDate(); } else if (Map.class.isAssignableFrom(objectClass)) { object = (T) randomMap((Class<Map>) objectClass, typeClass1, typeClass2); } else if (List.class.isAssignableFrom(objectClass)) { object = (T) randomList((Class<List>) objectClass, typeClass1); } else if (Set.class.isAssignableFrom(objectClass)) { object = (T) randomSet((Class<Set>) objectClass, typeClass1); } else if (Collection.class.isAssignableFrom(objectClass)) { object = (T) randomCollection((Class<Collection>) objectClass, typeClass1); } else if (objectClass.isArray()) { object = (T) randomArray(objectClass.getComponentType()); } else if (objectClass.isEnum()) { object = (T) randomEnum(objectClass); } else { object = objectClass.newInstance(); for (Field field : objectClass.getDeclaredFields()) { if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())) { Class fieldType = field.getType(); field.setAccessible(true); if (field.getGenericType() instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) field.getGenericType(); Type[] typeArgs = paramType.getActualTypeArguments(); if (typeArgs.length == 1) { if (typeArgs[0] instanceof ParameterizedType) { // TODO: HANDLE NESTED PARAM TYPE } else { field.set(object, randomObject(fieldType, (Class<?>) typeArgs[0])); } } else if (typeArgs.length == 2) { field.set(object, randomObject(fieldType, (Class<?>) typeArgs[0], (Class<?>) typeArgs[1])); } } else { field.set(object, randomObject(fieldType)); } } } } } catch (Exception ex) { //LOG.error("Exception while building the random object", ex); } return object; }
From source file:org.dcm4che3.conf.core.api.internal.ConfigReflection.java
private static ClassInfo scanClass(Class clazz) { ClassInfo classInfo = new ClassInfo(); classInfo.configurableProperties = new ArrayList<ConfigProperty>(); // scan all fields from this class and superclasses for (Field field : getAllFields(clazz)) { if (field.getAnnotation(ConfigurableProperty.class) != null) { ConfigProperty ap = new ConfigProperty(annotationsArrayToMap(field.getAnnotations()), field.getName(), field.getGenericType()); classInfo.configurableProperties.add(ap); if (ap.isUuid()) { if (classInfo.uuidProperty != null) { throw new IllegalArgumentException( "A configurable class MUST NOT have more than one UUID field - violated by class " + clazz.getName()); }/*from w w w . ja va 2 s. com*/ classInfo.uuidProperty = ap; } if (ap.isOlockHash()) { if (classInfo.olockHashProperty != null) { throw new IllegalArgumentException( "A configurable class MUST NOT have more than one optimistic locking hash field - violated by class " + clazz.getName()); } classInfo.olockHashProperty = ap; } } else if (field.getAnnotation(Parent.class) != null) { if (classInfo.parentField != null) { throw new IllegalArgumentException( "A configurable class MUST NOT have more than one field annotated with @Parent - violated by class " + clazz.getName()); } classInfo.parentField = field; } } if (!ConfigurableClassExtension.class.isAssignableFrom(clazz) && classInfo.uuidProperty == null && classInfo.parentField != null) { throw new IllegalArgumentException( "A configurable class that refers to a @Parent must have a uuid property defined (except the extensions). Violated by " + clazz.getName()); } return classInfo; }
From source file:org.openmrs.module.auditlog.util.AuditLogUtil.java
/** * Gets the class of the collection elements if the property with the specified name is a * collection/* w ww . j a v a 2s .co m*/ * * @param owningType the type the collection belongs to * @param propertyName the property name of the collection * @return the class of the elements of the matching property * @should return the class of the property */ public static Class<?> getCollectionElementType(Class<?> owningType, String propertyName) { Field field = getField(owningType, propertyName); if (field != null) { if (Collection.class.isAssignableFrom(field.getType())) { Type type = field.getGenericType(); if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; if (!ArrayUtils.isEmpty(pt.getActualTypeArguments())) { return (Class<?>) pt.getActualTypeArguments()[0]; } } } } else { log.warn("Failed to find property " + propertyName + " in class " + owningType.getName()); } return null; }
From source file:org.dcm4che3.conf.core.util.ConfigIterators.java
private static List<AnnotatedConfigurableProperty> processAnnotatedProperties(Class clazz) { List<AnnotatedConfigurableProperty> l; l = new ArrayList<AnnotatedConfigurableProperty>(); // scan all fields from this class and superclasses for (Field field : getFieldsUpTo(clazz, null)) { if (field.getAnnotation(ConfigurableProperty.class) != null) { AnnotatedConfigurableProperty ap = new AnnotatedConfigurableProperty(); ap.setAnnotations(annotationsArrayToMap(field.getAnnotations())); ap.setType(field.getGenericType()); ap.setName(field.getName()); l.add(ap);/* ww w . j a va2s . c o m*/ } } configurableFieldsCache.put(clazz, l); return l; }
From source file:net.elsched.utils.SettingsBinder.java
/** * Bind configuration parameters into Guice Module. * //from w w w . ja v a2s .c o m * @return a Guice module configured with setting support. * @throws ConfigurationException * on configuration error */ public static Module bindSettings(String propertiesFileKey, Class<?>... settingsArg) throws ConfigurationException { final CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); String propertyFile = config.getString(propertiesFileKey); if (propertyFile != null) { config.addConfiguration(new PropertiesConfiguration(propertyFile)); } List<Field> fields = new ArrayList<Field>(); for (Class<?> settings : settingsArg) { fields.addAll(Arrays.asList(settings.getDeclaredFields())); } // Reflect on settings class and absorb settings final Map<Setting, Field> settings = new LinkedHashMap<Setting, Field>(); for (Field field : fields) { if (!field.isAnnotationPresent(Setting.class)) { continue; } // Validate target type SettingTypeValidator typeHelper = supportedSettingTypes.get(field.getType()); if (typeHelper == null || !typeHelper.check(field.getGenericType())) { throw new IllegalArgumentException(field.getType() + " is not one of the supported setting types"); } Setting setting = field.getAnnotation(Setting.class); settings.put(setting, field); } // Now validate them List<String> missingProperties = new ArrayList<String>(); for (Setting setting : settings.keySet()) { if (setting.defaultValue().isEmpty()) { if (!config.containsKey(setting.name())) { missingProperties.add(setting.name()); } } } if (missingProperties.size() > 0) { StringBuilder error = new StringBuilder(); error.append("The following required properties are missing from the server configuration: "); error.append(Joiner.on(", ").join(missingProperties)); } // bundle everything up in an injectable guice module return new AbstractModule() { @Override protected void configure() { // We must iterate the settings a third time when binding. // Note: do not collapse these loops as that will damage // early error detection. The runtime is still O(n) in setting // count. for (Map.Entry<Setting, Field> entry : settings.entrySet()) { Class<?> type = entry.getValue().getType(); Setting setting = entry.getKey(); if (int.class.equals(type)) { Integer defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Integer.parseInt(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getInteger(setting.name(), defaultValue)); } else if (boolean.class.equals(type)) { Boolean defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Boolean.parseBoolean(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getBoolean(setting.name(), defaultValue)); } else if (String.class.equals(type)) { bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getString(setting.name(), setting.defaultValue())); } else { String[] value = config.getStringArray(setting.name()); if (value.length == 0 && !setting.defaultValue().isEmpty()) { value = setting.defaultValue().split(","); } bind(new TypeLiteral<List<String>>() { }).annotatedWith(Names.named(setting.name())).toInstance(ImmutableList.copyOf(value)); } } } }; }
From source file:org.waveprotocol.wave.util.settings.SettingsBinder.java
/** * Bind configuration parameters into Guice Module. * * @return a Guice module configured with setting support. * @throws ConfigurationException on configuration error *///from w w w. j a v a2s . co m public static Module bindSettings(String propertiesFileKey, Class<?>... settingsArg) throws ConfigurationException { final CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); String propertyFile = config.getString(propertiesFileKey); if (propertyFile != null) { config.addConfiguration(new PropertiesConfiguration(propertyFile)); } List<Field> fields = new ArrayList<Field>(); for (Class<?> settings : settingsArg) { fields.addAll(Arrays.asList(settings.getDeclaredFields())); } // Reflect on settings class and absorb settings final Map<Setting, Field> settings = new LinkedHashMap<Setting, Field>(); for (Field field : fields) { if (!field.isAnnotationPresent(Setting.class)) { continue; } // Validate target type SettingTypeValidator typeHelper = supportedSettingTypes.get(field.getType()); if (typeHelper == null || !typeHelper.check(field.getGenericType())) { throw new IllegalArgumentException(field.getType() + " is not one of the supported setting types"); } Setting setting = field.getAnnotation(Setting.class); settings.put(setting, field); } // Now validate them List<String> missingProperties = new ArrayList<String>(); for (Setting setting : settings.keySet()) { if (setting.defaultValue().isEmpty()) { if (!config.containsKey(setting.name())) { missingProperties.add(setting.name()); } } } if (missingProperties.size() > 0) { StringBuilder error = new StringBuilder(); error.append("The following required properties are missing from the server configuration: "); error.append(Joiner.on(", ").join(missingProperties)); throw new ConfigurationException(error.toString()); } // bundle everything up in an injectable guice module return new AbstractModule() { @Override protected void configure() { // We must iterate the settings a third time when binding. // Note: do not collapse these loops as that will damage // early error detection. The runtime is still O(n) in setting count. for (Map.Entry<Setting, Field> entry : settings.entrySet()) { Class<?> type = entry.getValue().getType(); Setting setting = entry.getKey(); if (int.class.equals(type)) { Integer defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Integer.parseInt(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getInteger(setting.name(), defaultValue)); } else if (boolean.class.equals(type)) { Boolean defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Boolean.parseBoolean(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getBoolean(setting.name(), defaultValue)); } else if (String.class.equals(type)) { bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getString(setting.name(), setting.defaultValue())); } else { String[] value = config.getStringArray(setting.name()); if (value.length == 0 && !setting.defaultValue().isEmpty()) { value = setting.defaultValue().split(","); } bind(new TypeLiteral<List<String>>() { }).annotatedWith(Names.named(setting.name())).toInstance(ImmutableList.copyOf(value)); } } } }; }
From source file:cc.kune.wave.server.CustomSettingsBinder.java
/** * Bind configuration parameters into Guice Module. * * @param propertyFile the property file * @param settingsArg the settings arg//w ww. ja v a 2 s.c o m * @return a Guice module configured with setting support. * @throws ConfigurationException on configuration error */ public static Module bindSettings(String propertyFile, Class<?>... settingsArg) throws ConfigurationException { final CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); config.addConfiguration(new PropertiesConfiguration(propertyFile)); List<Field> fields = new ArrayList<Field>(); for (Class<?> settings : settingsArg) { fields.addAll(Arrays.asList(settings.getDeclaredFields())); } // Reflect on settings class and absorb settings final Map<Setting, Field> settings = new LinkedHashMap<Setting, Field>(); for (Field field : fields) { if (!field.isAnnotationPresent(Setting.class)) { continue; } // Validate target type SettingTypeValidator typeHelper = supportedSettingTypes.get(field.getType()); if (typeHelper == null || !typeHelper.check(field.getGenericType())) { throw new IllegalArgumentException(field.getType() + " is not one of the supported setting types"); } Setting setting = field.getAnnotation(Setting.class); settings.put(setting, field); } // Now validate them List<String> missingProperties = new ArrayList<String>(); for (Setting setting : settings.keySet()) { if (setting.defaultValue().isEmpty()) { if (!config.containsKey(setting.name())) { missingProperties.add(setting.name()); } } } if (missingProperties.size() > 0) { StringBuilder error = new StringBuilder(); error.append("The following required properties are missing from the server configuration: "); error.append(Joiner.on(", ").join(missingProperties)); throw new ConfigurationException(error.toString()); } // bundle everything up in an injectable guice module return new AbstractModule() { @Override protected void configure() { // We must iterate the settings a third time when binding. // Note: do not collapse these loops as that will damage // early error detection. The runtime is still O(n) in setting count. for (Map.Entry<Setting, Field> entry : settings.entrySet()) { Class<?> type = entry.getValue().getType(); Setting setting = entry.getKey(); if (int.class.equals(type)) { Integer defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Integer.parseInt(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getInteger(setting.name(), defaultValue)); } else if (boolean.class.equals(type)) { Boolean defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Boolean.parseBoolean(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getBoolean(setting.name(), defaultValue)); } else if (String.class.equals(type)) { bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getString(setting.name(), setting.defaultValue())); } else { String[] value = config.getStringArray(setting.name()); if (value.length == 0 && !setting.defaultValue().isEmpty()) { value = setting.defaultValue().split(","); } bind(new TypeLiteral<List<String>>() { }).annotatedWith(Names.named(setting.name())).toInstance(ImmutableList.copyOf(value)); } } } }; }