List of usage examples for java.lang.reflect Field getType
public Class<?> getType()
From source file:net.elsched.utils.SettingsBinder.java
/** * Bind configuration parameters into Guice Module. * /*from ww w . ja va 2s. c om*/ * @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:com.titilink.camel.rest.util.CommonUtils.java
/** * ?// w w w .j a v a 2 s.c o m * * @param instance * @param <T> * @throws OperationException */ private static <T> void trimAndCheckParameter(T instance) throws OperationException { if (null == instance) { return; } if ((!instance.getClass().getName().startsWith(PACKAGE_NAME_PREFIX)) && instance.getClass() != List.class) { return; } Field[] fields = instance.getClass().getDeclaredFields(); String value = null; for (Field field : fields) { field.setAccessible(true); try { if (field.getType().getName().startsWith(PACKAGE_NAME_PREFIX)) { trimAndCheckParameter(field.get(instance)); } else if (field.getType() == String.class) { value = (String) field.get(instance); if (null != value) { field.set(instance, value.trim()); } } else if (field.getType() == List.class) { List<T> list = (List<T>) field.get(instance); if (null != list) { for (T t : list) { trimAndCheckParameter(t); } } } } catch (OperationException e) { LOGGER.error("trimAndCheckParameter method error, trim exception field={}, instance={}", field, instance); LOGGER.error("trimAndCheckParameter method error, trim exception e=", e); throw new OperationException(Status.CLIENT_ERROR_BAD_REQUEST.getCode(), e.getErrorCode(), e.getMessage()); } catch (Exception e) { LOGGER.error("trimAndCheckParameter method error, trim exception field={}, instance={}", field, instance); LOGGER.error("trimAndCheckParameter method error, trim exception e=", e); throw new OperationException(CommonCode.INVALID_INPUT_PARAMETER, "Invalid input params"); } } // ?? checkParameter(instance); }
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/*from w w w. jav a2 s. c om*/ * @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)); } } } }; }
From source file:com.conversantmedia.mapreduce.tool.DistributedResourceManager.java
private static Object getResourceValue(Field field, String valueString, String originalTypeClassname, Path[] distFiles) throws IOException, ClassNotFoundException { // First, determine our approach: Object value = null;/*from w w w .ja v a 2 s . c o m*/ if (field.getType().isAssignableFrom(String.class)) { value = valueString; } else if (ClassUtils.isPrimitiveOrWrapper(field.getType())) { value = ConvertUtils.convert(valueString, field.getType()); } else { Path path = distributedFilePath(valueString, distFiles); // This is something on the distributed cache (or illegal) if (field.getType() == Path.class) { value = path; } else if (field.getType() == File.class) { value = new File(path.toUri()); } // Deserialize .ser file else if (field.getType().isAssignableFrom(Class.forName(originalTypeClassname))) { ObjectInputStream in = null; try { File beanSerFile = new File(path.toUri().getPath()); FileInputStream fileIn = new FileInputStream(beanSerFile); in = new ObjectInputStream(fileIn); value = in.readObject(); } finally { IOUtils.closeQuietly(in); } } else { throw new IllegalArgumentException("Cannot locate resource for field [" + field.getName() + "]"); } } return value; }
From source file:com.fengduo.bee.commons.util.StringFormatter.java
public static Object objectFieldEscape(Object ob) { Field[] fields = BeanUtils.getAllFields(null, ob.getClass()); for (Field field : fields) { if (field == null || field.getName() == null || field.getType() == null) { continue; }/* w ww. j a va 2 s .c om*/ if (StringUtils.equals("serialVersionUID", field.getName())) { continue; } if (!StringUtils.equals(field.getType().getSimpleName(), "String")) { continue; } try { Object fieldVal = PropertyUtils.getProperty(ob, field.getName()); if (null == fieldVal) { continue; } field.setAccessible(true); String value = (String) fieldVal; PropertyUtils.setProperty(ob, field.getName(), StringEscapeUtils.escapeXml(value)); } catch (Exception e) { e.printStackTrace(); } } return ob; }
From source file:com.fengduo.bee.commons.util.StringFormatter.java
public static Object objectFieldBr(Object ob) { Field[] fields = BeanUtils.getAllFields(null, ob.getClass()); for (Field field : fields) { if (field == null || field.getName() == null || field.getType() == null) { continue; }/*www. j a v a 2 s . c o m*/ if (StringUtils.equals("serialVersionUID", field.getName())) { continue; } if (!StringUtils.equals(field.getType().getSimpleName(), "String")) { continue; } try { Object fieldVal = PropertyUtils.getProperty(ob, field.getName()); if (null == fieldVal) { continue; } field.setAccessible(true); String value = (String) fieldVal; PropertyUtils.setProperty(ob, field.getName(), value.replaceAll("\r\n", "<br/>")); } catch (Exception e) { e.printStackTrace(); } } return ob; }
From source file:com.amazonaws.services.iot.client.shadow.AwsIotJsonSerializer.java
private static Object invokeGetterMethod(Object target, Field field) throws IOException { String fieldName = Character.toUpperCase(field.getName().charAt(0)) + field.getName().substring(1); String getter = "get" + fieldName; Method method;//from ww w . java 2s .c o m try { method = target.getClass().getMethod(getter); } catch (NoSuchMethodException | SecurityException e) { if (e instanceof NoSuchMethodException && boolean.class.equals(field.getType())) { getter = "is" + fieldName; try { method = target.getClass().getMethod(getter); } catch (NoSuchMethodException | SecurityException ie) { throw new IllegalArgumentException(ie); } } else { throw new IllegalArgumentException(e); } } Object value; try { value = method.invoke(target); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IOException(e); } return value; }
From source file:Main.java
public static void setValue(Object obj, String fieldName, Object value) { if (obj == null || TextUtils.isEmpty(fieldName)) { return;//from w w w. j av a 2 s . co m } try { // Field field = obj.getClass().getDeclaredField(fieldName); Field field = getDeclaredField(obj, fieldName); Object realValue = value; if (value instanceof BigDecimal || value instanceof Number || value instanceof String) { if (field.getType() == Float.class || field.getType() == float.class) { realValue = Float.parseFloat(value.toString()); } else if (field.getType() == Double.class || field.getType() == double.class) { realValue = Double.parseDouble(value.toString()); } else if (field.getType() == Integer.class || field.getType() == int.class) { realValue = (int) Double.parseDouble(value.toString()); } else if (field.getType() == Boolean.class || field.getType() == boolean.class) { realValue = Boolean.valueOf(value.toString()); } } if (field.getType() == boolean.class || field.getType() == Boolean.class) { if (value != null) { realValue = Boolean.valueOf(value.toString()); } } setProperty(obj, field, realValue); } catch (Exception e) { return; } }
From source file:org.appverse.web.framework.backend.api.converters.helpers.ConverterUtils.java
/** * Copy source bean single properties to target bean * // w w w . j a va 2 s. c om * @param source * Source Bean * @param target * Target Bean * @param sourceFields * Fields of source Bean * @throws Exception */ private static void copyPlainFields(AbstractBean source, AbstractBean target, Field[] sourceFields) throws Exception { String[] ignoreProperties = new String[0]; // For each source field... for (Field field : sourceFields) { // If source field is a bean... if (AbstractBean.class.isAssignableFrom(field.getType())) { // Put it in ignore properties ignoreProperties = (String[]) ArrayUtils.add(ignoreProperties, field.getName()); } } // Copy properties with Spring Framework copy properties org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties); }
From source file:ReflectionUtils.java
public static Class<?> getTargetType(Field field) { // Generic type, case when we have a Collection of ? if (field.getGenericType() instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) field.getGenericType(); if (type.getActualTypeArguments().length == 1 && type.getActualTypeArguments()[0] instanceof Class) return (Class<?>) type.getActualTypeArguments()[0]; }// ww w .ja v a 2 s .co m return field.getType(); }