List of usage examples for java.lang.reflect Field getType
public Class<?> getType()
From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java
/** * Given a JSONObject, unmarhall it to an instance of the given class. * * @param jsonObj JSON string to unmarshall. * @param cls Return an instance of this class. Must be either public class * or private static class. Inner class will not work. * @param <T> Same type as cls.// w w w . j av a2 s .com * @return An instance of class given by cls. * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException */ public static <T> T JSONToObj(JSONObject jsonObj, Class<T> cls) { T result = null; try { Constructor<T> constructor = cls.getDeclaredConstructor(); constructor.setAccessible(true); result = (T) constructor.newInstance(); Iterator<?> i = jsonObj.keys(); while (i.hasNext()) { String k = (String) i.next(); Object val = jsonObj.get(k); try { Field field = cls.getField(k); Object converted = valToType(val, field.getGenericType()); if (converted == null) { if (!field.getType().isPrimitive()) { field.set(result, null); } else { throw new TypeMismatchException( String.format("Type %s cannot be set to null.", field.getType())); } } else { if (converted instanceof List && field.getType().isAssignableFrom(List.class)) { // Class can define their own favorite // implementation of List. In which case the field // still need to be defined as List, but it can be // initialized with a placeholder instance of any of // the List implementations (eg. ArrayList). Object existing = field.get(result); if (existing != null) { ((List<?>) existing).clear(); // Just because I don't want javac to complain // about unsafe operations. So I'm gonna use // more reflection, HA! Method addAll = existing.getClass().getMethod("addAll", Collection.class); addAll.invoke(existing, converted); } else { field.set(result, converted); } } else { field.set(result, converted); } } } catch (NoSuchFieldException e) { // Ignore. } catch (IllegalAccessException e) { // Ignore. } catch (IllegalArgumentException e) { // Ignore. } } } catch (JSONException e) { throw new ParserException(e); } catch (NoSuchMethodException e) { throw new ClassInstantiationException("Failed to retrieve constructor for " + cls.toString() + ", make sure it's not an inner class."); } catch (InstantiationException e) { throw new ClassInstantiationException(cls); } catch (IllegalAccessException e) { throw new ClassInstantiationException(cls); } catch (InvocationTargetException e) { throw new ClassInstantiationException(cls); } return result; }
From source file:cn.afterturn.easypoi.util.PoiPublicUtil.java
/** * /* www . j a va 2s .c o m*/ * * @param clazz * @return */ public static Object createObject(Class<?> clazz, String targetId) { Object obj = null; try { if (clazz.equals(Map.class)) { return new LinkedHashMap<String, Object>(); } obj = clazz.newInstance(); Field[] fields = getClassFields(clazz); for (Field field : fields) { if (isNotUserExcelUserThis(null, field, targetId)) { continue; } if (isCollection(field.getType())) { ExcelCollection collection = field.getAnnotation(ExcelCollection.class); PoiReflectorUtil.fromCache(clazz).setValue(obj, field.getName(), collection.type().newInstance()); } else if (!isJavaClass(field) && !field.getType().isEnum()) { PoiReflectorUtil.fromCache(clazz).setValue(obj, field.getName(), createObject(field.getType(), targetId)); } } } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(""); } return obj; }
From source file:com.plusub.lib.annotate.JsonParserUtils.java
/** * ??/* w ww . jav a2s . co m*/ * <p>Title: setSingleValue * <p>Description: * @param object * @param field * @param jsonObj JSON * @param name ?JSON * @throws Exception */ private static void setSingleValue(Object object, Field field, JSONObject jsonObj, String name) throws Exception { //? if (!isBaseDataType(field.getType())) { JSONObject jo = JSONUtils.getJSONObject(jsonObj, name, null); if (jo != null) { Object result = parserField(getInstance(field.getType().getName()), jo); if (result != null) { setFieldValue(object, field, result); } } } else { setFieldValue(object, field, JSONUtils.get(jsonObj, name, null)); } }
From source file:com.kcs.core.utilities.Utility.java
public static void nullToEmptyString(final Object obj) { ReflectionUtils.doWithFields(obj.getClass(), new ReflectionUtils.FieldCallback() { @Override//www. j a v a 2 s . co m public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { field.setAccessible(true); if (Utility.isNull(field.get(obj))) { Class<?> clazz = field.getType(); if (clazz == String.class) { field.set(obj, StringUtil.BLANK); } } } }); }
From source file:ca.uhn.fhir.context.ModelScanner.java
static Class<?> determineElementType(Field next) { Class<?> nextElementType = next.getType(); if (List.class.equals(nextElementType)) { nextElementType = ReflectionUtil.getGenericCollectionTypeOfField(next); } else if (Collection.class.isAssignableFrom(nextElementType)) { throw new ConfigurationException( "Field '" + next.getName() + "' in type '" + next.getClass().getCanonicalName() + "' is a Collection - Only java.util.List curently supported"); }//from w w w . jav a 2 s. c o m return nextElementType; }
From source file:edu.brown.utils.ClassUtil.java
/** * @param clazz//from ww w . ja va2 s . co m * @return */ public static <T> Field[] getFieldsByType(Class<?> clazz, Class<? extends T> fieldType) { List<Field> fields = new ArrayList<Field>(); for (Field f : clazz.getDeclaredFields()) { int modifiers = f.getModifiers(); if (Modifier.isTransient(modifiers) == false && Modifier.isPublic(modifiers) == true && Modifier.isStatic(modifiers) == false && ClassUtil.getSuperClasses(f.getType()).contains(fieldType)) { fields.add(f); } } // FOR return (fields.toArray(new Field[fields.size()])); }
From source file:io.tilt.minka.utils.Defaulter.java
private static PropertyEditor edit(final Properties props, final Object configurable, final Field staticField, final Field instanceField) throws IllegalAccessException { staticField.setAccessible(true);/*from w ww .ja v a 2s.co m*/ final String name = instanceField.getName(); final String staticValue = staticField.get(configurable).toString(); final Object propertyOrDefault = props.getProperty(name, System.getProperty(name, staticValue)); final String objName = configurable.getClass().getSimpleName(); final PropertyEditor editor = PropertyEditorManager.findEditor(instanceField.getType()); final String setLog = "Defaulter: set <{}> field [{}] = '{}' from {} "; try { editor.setAsText(propertyOrDefault.toString()); logger.info(setLog, objName, name, editor.getValue(), propertyOrDefault != staticValue ? " property " : staticField.getName()); } catch (Exception e) { logger.error( "Defaulter: object <{}> field: {} does not accept property or static " + "default value: {} (reason: {})", objName, name, propertyOrDefault, e.getClass().getSimpleName()); try { // at this moment only prop. might've been failed editor.setAsText(staticValue); logger.info(setLog, objName, name, editor.getValue(), staticField.getName()); } catch (Exception e2) { final StringBuilder sb = new StringBuilder().append("Defaulter: object <").append(objName) .append("> field: ").append(name).append(" does not accept static default value: ") .append(propertyOrDefault).append(" (reason: ").append(e.getClass().getSimpleName()) .append(")"); throw new RuntimeException(sb.toString()); } } return editor; }
From source file:org.lendingclub.mercator.docker.SwarmScanner.java
/** * The Docker java client is significantly behind the server API. Rather * than try to fork/patch our way to success, we just implement a bit of * magic to get access to the underlying jax-rs WebTarget. * //from w w w. j av a 2 s . co m * Docker should just expose this as a public method. * * @param c * @return */ public static WebTarget extractWebTarget(DockerClient c) { try { for (Field m : DockerClientImpl.class.getDeclaredFields()) { if (DockerCmdExecFactory.class.isAssignableFrom(m.getType())) { m.setAccessible(true); JerseyDockerCmdExecFactory f = (JerseyDockerCmdExecFactory) m.get(c); Method method = f.getClass().getDeclaredMethod("getBaseResource"); method.setAccessible(true); return (WebTarget) method.invoke(f); } } } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalStateException("could not obtain WebTarget", e); } throw new IllegalStateException("could not obtain WebTarget"); }
From source file:be.fedict.eid.applet.service.AppletServiceServlet.java
public static void injectInitParams(ServletConfig config, MessageHandler<?> messageHandler) throws ServletException, IllegalArgumentException, IllegalAccessException { Class<?> messageHandlerClass = messageHandler.getClass(); Field[] fields = messageHandlerClass.getDeclaredFields(); for (Field field : fields) { InitParam initParamAnnotation = field.getAnnotation(InitParam.class); if (null == initParamAnnotation) { continue; }//from www .j av a2s .com String initParamName = initParamAnnotation.value(); Class<?> fieldType = field.getType(); field.setAccessible(true); if (ServiceLocator.class.equals(fieldType)) { /* * We always inject a service locator. */ ServiceLocator<Object> fieldValue = new ServiceLocator<Object>(initParamName, config); field.set(messageHandler, fieldValue); continue; } String initParamValue = config.getInitParameter(initParamName); if (initParamAnnotation.required() && null == initParamValue) { throw new ServletException("missing required init-param: " + initParamName + " for message handler:" + messageHandlerClass.getName()); } if (null == initParamValue) { continue; } if (Boolean.TYPE.equals(fieldType)) { LOG.debug("injecting boolean: " + initParamValue); Boolean fieldValue = Boolean.parseBoolean(initParamValue); field.set(messageHandler, fieldValue); continue; } if (String.class.equals(fieldType)) { field.set(messageHandler, initParamValue); continue; } if (InetAddress.class.equals(fieldType)) { InetAddress inetAddress; try { inetAddress = InetAddress.getByName(initParamValue); } catch (UnknownHostException e) { throw new ServletException("unknown host: " + initParamValue); } field.set(messageHandler, inetAddress); continue; } if (Long.class.equals(fieldType)) { Long fieldValue = Long.parseLong(initParamValue); field.set(messageHandler, fieldValue); continue; } throw new ServletException("unsupported init-param field type: " + fieldType.getName()); } }
From source file:org.cybercat.automation.annotations.AnnotationBuilder.java
/** * @param targetObject/* w ww .ja va 2 s .com*/ * @param fields * @return * @throws AutomationFrameworkException * @throws PageObjectException */ @SuppressWarnings("unchecked") private static <T extends AbstractPageObject> T createPageObjectField(Object targetObject, Field field) throws AutomationFrameworkException, PageObjectException { AutomationMain mainFactory = AutomationMain.getMainFactory(); PageFactory pageFactory = mainFactory.getPageFactory(); Class<AbstractPageObject> clazz; try { clazz = (Class<AbstractPageObject>) field.getType(); } catch (Exception e) { throw new AutomationFrameworkException("Unexpected field type :" + field.getType().getSimpleName() + " field name: " + field.getName() + " class: " + targetObject.getClass().getSimpleName() + " Thread ID:" + Thread.currentThread().getId() + " \n\tThis field must be of the type that extends AbstractPageObject class.", e); } try { T po = (T) pageFactory.createPage(clazz); po.setPageFactory(pageFactory); field.set(targetObject, po); return po; } catch (Exception e) { throw new AutomationFrameworkException( "Set filed exception. Please, save this log and contact the Cybercat project support." + " field name: " + field.getName() + " class: " + targetObject.getClass().getSimpleName() + " Thread ID:" + Thread.currentThread().getId(), e); } }