List of usage examples for java.lang.reflect Field getType
public Class<?> getType()
From source file:it.delli.mwebc.servlet.MWebCRenderer.java
public static void buildLayout(Element elem, Widget parent, Page page) throws Exception { Widget widget = null;/*from w w w.ja v a 2 s . co m*/ if (elem.getNodeType() == Node.ELEMENT_NODE && elem.getNodeName().equals("Page")) { for (int j = 0; j < elem.getAttributes().getLength(); j++) { Node attribute = elem.getAttributes().item(j); if (!attribute.getNodeName().equals("id")) { if (attribute.getNodeName().equals("eventListener")) { log.debug("Setting PageEventListener"); try { page.setEventListener( (PageEventListener) Class.forName(attribute.getNodeValue()).newInstance()); } catch (Exception e) { log.error("Exception in setting PageEventListener"); } } } } if (page.getEventListener() == null) { log.debug("Setting default PageEventListener"); page.setEventListener(new PageEventListener() { @Override public void onLoad(Event event) { } @Override public void onInit(Event event) { } }); } for (int i = 0; i < elem.getChildNodes().getLength(); i++) { Node node = elem.getChildNodes().item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { buildLayout((Element) node, widget, page); } } } else if (elem.getNodeType() == Node.ELEMENT_NODE && elem.getNodeName().equals("PageFragment")) { for (int i = 0; i < elem.getChildNodes().getLength(); i++) { Node node = elem.getChildNodes().item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { buildLayout((Element) node, parent, page); } } } else { Class<?> widgetClass = page.getApplication().getWidgetClass(elem.getNodeName()); if (widgetClass == null) { log.fatal("Exception in getting widget class for widget " + elem.getNodeName()); throw new Exception(); } else if (widgetClass.getName().equals("com.dodifferent.applications.commander.widget.DataListItem")) { System.out.println(); } CastHelper castHelper = page.getApplication().getCastHelper(widgetClass); String id = null; for (int j = 0; j < elem.getAttributes().getLength(); j++) { Node attribute = elem.getAttributes().item(j); if (attribute.getNodeName().equals("id")) { id = attribute.getNodeValue(); break; } } HashMap<String, Object> initParams = new HashMap<String, Object>(); for (int j = 0; j < elem.getAttributes().getLength(); j++) { Node attributeNode = elem.getAttributes().item(j); if (!attributeNode.getNodeName().equals("id") && !attributeNode.getNodeName().startsWith("on")) { Field fieldAttribute = ReflectionUtils.getAnnotatedField(widgetClass, attributeNode.getNodeName(), WidgetAttribute.class); if (fieldAttribute != null) { fieldAttribute.setAccessible(true); Class<?> propertyType = fieldAttribute.getType(); // Type[] genericTypes = ((ParameterizedType)fieldAttribute.getGenericType()).getActualTypeArguments(); initParams.put(attributeNode.getNodeName(), castHelper.toType(attributeNode.getNodeValue(), propertyType)); } else { log.warn("Warning in updating server widgets attribute. The attribute '" + attributeNode.getNodeName() + "' doesn't exist for widget " + widgetClass.getName()); } } } try { if (id != null && initParams.keySet().size() == 0) { Class[] constructorParams = { Page.class, String.class }; Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName()) .getConstructor(constructorParams); widget = (Widget) widgetConstructor.newInstance(page, id); } else if (id != null && initParams.keySet().size() > 0) { Class[] constructorParams = { Page.class, String.class, Map.class }; Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName()) .getConstructor(constructorParams); widget = (Widget) widgetConstructor.newInstance(page, id, initParams); } else if (id == null && initParams.keySet().size() == 0) { Class[] constructorParams = { Page.class }; Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName()) .getConstructor(constructorParams); widget = (Widget) widgetConstructor.newInstance(page); } else if (id == null && initParams.keySet().size() > 0) { Class[] constructorParams = { Page.class, Map.class }; Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName()) .getConstructor(constructorParams); widget = (Widget) widgetConstructor.newInstance(page, initParams); } } catch (Exception e) { log.error("Exception in constructing widget " + widget.getClass().getName() + " (" + widget.getId() + ")", e); } if (widget != null) { for (int j = 0; j < elem.getAttributes().getLength(); j++) { Node attributeNode = elem.getAttributes().item(j); if (!attributeNode.getNodeName().equals("id") && attributeNode.getNodeName().startsWith("on")) { String event = attributeNode.getNodeName(); try { widget.addEventListener(event, page.getEventListener(), attributeNode.getNodeValue()); // Method eventMethod = widget.getClass().getMethod("addEventListener", String.class, EventListener.class, String.class); // eventMethod.invoke(widget, event, page.getEventListener(), attributeNode.getNodeValue()); } catch (Exception e) { log.warn("Warning in registering EventListener for widget " + widget.getClass().getName() + " (" + widget.getId() + ")", e); } } } for (int i = 0; i < elem.getChildNodes().getLength(); i++) { Node node = elem.getChildNodes().item(i); if (node.getNodeType() == Node.CDATA_SECTION_NODE || node.getNodeType() == Node.TEXT_NODE) { try { String content = node.getNodeValue().replace("\t", "").replace("\n", "").replace("\"", "\\\""); if (!content.equals("")) { // Method attributeMethod = widget.getClass().getMethod("addTextContent", String.class); // attributeMethod.invoke(widget, content); widget.addTextContent(content); } } catch (Exception e) { log.warn("Warning in setting content for widget " + widget.getClass().getName() + " (" + widget.getId() + ")", e); } } else if (node.getNodeType() == Node.ELEMENT_NODE) { buildLayout((Element) node, widget, page); } } widget.setParent(parent); } } }
From source file:edu.usu.sdl.openstorefront.doc.EntityProcessor.java
private static void addFields(Class entity, EntityDocModel docModel) { if (entity != null) { Field[] fields = entity.getDeclaredFields(); for (Field field : fields) { //Skip static field if ((Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) == false) { EntityFieldModel fieldModel = new EntityFieldModel(); fieldModel.setName(field.getName()); fieldModel.setType(field.getType().getSimpleName()); fieldModel.setOriginClass(entity.getSimpleName()); fieldModel.setEmbeddedType(ReflectionUtil.isComplexClass(field.getType())); if (ReflectionUtil.isCollectionClass(field.getType())) { DataType dataType = (DataType) field.getAnnotation(DataType.class); if (dataType != null) { String typeClass = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeClass = dataType.actualClassName(); }//w w w. ja va 2 s . c o m fieldModel.setGenericType(typeClass); } } APIDescription description = (APIDescription) field.getAnnotation(APIDescription.class); if (description != null) { fieldModel.setDescription(description.value()); } for (Annotation annotation : field.getAnnotations()) { if (annotation.annotationType().getName().equals(APIDescription.class.getName()) == false) { EntityConstraintModel entityConstraintModel = new EntityConstraintModel(); entityConstraintModel.setName(annotation.annotationType().getSimpleName()); APIDescription annotationDescription = (APIDescription) annotation.annotationType() .getAnnotation(APIDescription.class); if (annotationDescription != null) { entityConstraintModel.setDescription(annotationDescription.value()); } //rules Object annObj = field.getAnnotation(annotation.annotationType()); if (annObj instanceof NotNull) { entityConstraintModel.setRules("Field is required"); } else if (annObj instanceof PK) { PK pk = (PK) annObj; entityConstraintModel.setRules("<b>Generated:</b> " + pk.generated()); fieldModel.setPrimaryKey(true); } else if (annObj instanceof FK) { FK fk = (FK) annObj; StringBuilder sb = new StringBuilder(); sb.append("<b>Foreign Key:</b> ").append(fk.value().getSimpleName()); sb.append(" (<b>Enforce</b>: ").append(fk.enforce()); sb.append(" <b>Soft reference</b>: ").append(fk.softReference()); if (StringUtils.isNotBlank(fk.referencedField())) { sb.append(" <b>Reference Field</b>: ").append(fk.referencedField()); } sb.append(" )"); entityConstraintModel.setRules(sb.toString()); } else if (annObj instanceof ConsumeField) { entityConstraintModel.setRules(""); } else if (annObj instanceof Size) { Size size = (Size) annObj; entityConstraintModel .setRules("<b>Min:</b> " + size.min() + " <b>Max:</b> " + size.max()); } else if (annObj instanceof Pattern) { Pattern pattern = (Pattern) annObj; entityConstraintModel.setRules("<b>Pattern:</b> " + pattern.regexp()); } else if (annObj instanceof Sanitize) { Sanitize sanitize = (Sanitize) annObj; entityConstraintModel .setRules("<b>Sanitize:</b> " + sanitize.value().getSimpleName()); } else if (annObj instanceof Unique) { Unique unique = (Unique) annObj; entityConstraintModel.setRules("<b>Handler:</b> " + unique.value().getSimpleName()); } else if (annObj instanceof ValidValueType) { ValidValueType validValueType = (ValidValueType) annObj; StringBuilder sb = new StringBuilder(); if (validValueType.value().length > 0) { sb.append(" <b>Values:</b> ").append(Arrays.toString(validValueType.value())); } if (validValueType.lookupClass().length > 0) { sb.append(" <b>Lookups:</b> "); for (Class lookupClass : validValueType.lookupClass()) { sb.append(lookupClass.getSimpleName()).append(" "); } } if (validValueType.enumClass().length > 0) { sb.append(" <b>Enumerations:</b> "); for (Class enumClass : validValueType.enumClass()) { sb.append(enumClass.getSimpleName()).append(" ("); sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")"); } } entityConstraintModel.setRules(sb.toString()); } else if (annObj instanceof Min) { Min min = (Min) annObj; entityConstraintModel.setRules("<b>Min value:</b> " + min.value()); } else if (annObj instanceof Max) { Max max = (Max) annObj; entityConstraintModel.setRules("<b>Max value:</b> " + max.value()); } else if (annObj instanceof Version) { entityConstraintModel.setRules("Entity version; For Multi-Version control"); } else if (annObj instanceof DataType) { DataType dataType = (DataType) annObj; String typeClass = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeClass = dataType.actualClassName(); } entityConstraintModel.setRules("<b>Type:</b> " + typeClass); } else { entityConstraintModel.setRules(annotation.toString()); } //Annotations that have related classes if (annObj instanceof DataType) { DataType dataType = (DataType) annObj; entityConstraintModel.getRelatedClasses().add(dataType.value().getSimpleName()); } if (annObj instanceof FK) { FK fk = (FK) annObj; entityConstraintModel.getRelatedClasses().add(fk.value().getSimpleName()); } if (annObj instanceof ValidValueType) { ValidValueType validValueType = (ValidValueType) annObj; for (Class lookupClass : validValueType.lookupClass()) { entityConstraintModel.getRelatedClasses().add(lookupClass.getSimpleName()); } StringBuilder sb = new StringBuilder(); for (Class enumClass : validValueType.enumClass()) { sb.append("<br>"); sb.append(enumClass.getSimpleName()).append(": ("); sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")"); } entityConstraintModel .setRules(entityConstraintModel.getRules() + " " + sb.toString()); } fieldModel.getConstraints().add(entityConstraintModel); } } docModel.getFieldModels().add(fieldModel); } } addFields(entity.getSuperclass(), docModel); } }
From source file:com.plusub.lib.annotate.JsonParserUtils.java
/** * ?//from w ww. jav a2 s . c o m * <p>Title: getType * <p>Description: * @param field ? * @param defaultValue (Json?String) * @return defaultValue?obj */ private static Object getType(Field field, Object defaultValue, String fieldName) { Object value = defaultValue; if (showLog) { Logger.i(TAG, "getType:" + field.getName() + " " + field.getType().getName() + " " + " " + defaultValue); } if (defaultValue == null) { return value; } String type = field.getType().getName(); Class clazz = field.getType(); try { if (isBaseDataType(field.getType())) { String str = defaultValue + ""; if (clazz.equals(String.class)) { value = defaultValue; } else if (clazz.equals(Integer.class) || type.equals("int")) { value = Integer.parseInt(str); } else if (clazz.equals(Boolean.class) || type.equals("boolean")) { String defaultStr = str; String result = defaultStr.toLowerCase(); if (result.equals("true")) { value = true; } else if (result.equals("false")) { value = false; } else { value = Integer.parseInt(result) > 0 ? true : false; } } else if (clazz.equals(Double.class) || type.equals("double")) { value = Double.parseDouble(str); } else if (clazz.equals(Float.class) || type.equals("float")) { value = Float.parseFloat(str); } else if (clazz.equals(Short.class) || type.equals("short")) { value = Short.parseShort(str); } else if (clazz.equals(Long.class) || type.equals("long")) { value = Long.parseLong(str); } else if (clazz.equals(Byte.class) || type.equals("byte")) { value = Byte.parseByte(str); } } else { //? if (showLog) { Logger.i(TAG, "?, " + defaultValue); } } } catch (Exception e) { // TODO: handle exception if (showLog) { Logger.e(TAG, "?" + fieldName + "String-->" + field.getType().getName() + ", " + value); e.printStackTrace(); } return value; } return value; }
From source file:com.impetus.kundera.metadata.MetadataUtils.java
/** * Gets the embedded collection instance. * /*from www.j a v a 2s . c om*/ * @param embeddedCollectionField * the embedded collection field * @return the embedded collection instance */ public static Collection getEmbeddedCollectionInstance(Field embeddedCollectionField) { Collection embeddedCollection = null; Class embeddedCollectionFieldClass = embeddedCollectionField.getType(); if (embeddedCollection == null || embeddedCollection.isEmpty()) { if (embeddedCollectionFieldClass.equals(List.class)) { embeddedCollection = new ArrayList<Object>(); } else if (embeddedCollectionFieldClass.equals(Set.class)) { embeddedCollection = new HashSet<Object>(); } else { throw new InvalidEntityDefinitionException( "Field " + embeddedCollectionField.getName() + " must be either instance of List or Set"); } } return embeddedCollection; }
From source file:es.logongas.ix3.util.ReflectionUtil.java
/** * Obtiene una anotacin de una clase. La anotacin se obtiene de la * propiedad o del mtodo//from www.j av a 2 s. com * * @param <T> * @param baseClass La clase en la que se busca la anotacin * @param propertyName El nombre de la propiedad sobre la que se busca la * anotacin * @param annotationClass El tipo de anotacin a buscar * @return Retorna la anotacin.Si la anotacin existe tanto en la propiedad * como en el mtodo se retorna solo el de la propiedad. */ static public <T extends Annotation> T getAnnotation(Class baseClass, String propertyName, Class<T> annotationClass) { if (annotationClass == null) { throw new IllegalArgumentException("El argumento annotationClass no puede ser null"); } if (baseClass == null) { return null; } if ((propertyName == null) || (propertyName.trim().equals(""))) { throw new IllegalArgumentException("El argumento propertyName no puede ser null"); } String leftPropertyName; //El nombre de la propiedad antes del primer punto String rigthPropertyName; //El nombre de la propiedad antes del primer punto int indexPoint = propertyName.indexOf("."); if (indexPoint < 0) { leftPropertyName = propertyName; rigthPropertyName = null; } else if ((indexPoint > 0) && (indexPoint < (propertyName.length() - 1))) { leftPropertyName = propertyName.substring(0, indexPoint); rigthPropertyName = propertyName.substring(indexPoint + 1); } else { throw new RuntimeException("El punto no puede estar ni al principio ni al final"); } if (rigthPropertyName != null) { Field leftField = getField(baseClass, leftPropertyName); if (leftField == null) { throw new RuntimeException( "No existe el campo " + leftPropertyName + " en la clase " + baseClass.getName()); } return getAnnotation(leftField.getType(), rigthPropertyName, annotationClass); } else { T annotationField = getFieldAnnotation(baseClass, leftPropertyName, annotationClass); if (annotationField != null) { return annotationField; } T annotationMethod = getMethodAnnotation(baseClass, leftPropertyName, annotationClass); if (annotationMethod != null) { return annotationMethod; } //No hemos encontrado la anotacin return null; } }
From source file:com.qingstor.sdk.utils.QSJSONUtil.java
private static void setParameterToMap(Method m, Object source, Field f, Object data) { if (data != null) { try {// w ww .j a v a 2s.co m if (data instanceof JSONArray || data instanceof JSONObject) { Class fClass = f.getType(); if (fClass.equals(List.class)) { List invokeData = new ArrayList(); ParameterizedType stringListType = (ParameterizedType) f.getGenericType(); Class<?> cls = (Class<?>) stringListType.getActualTypeArguments()[0]; if (cls.equals(String.class) || cls.equals(Integer.class) || cls.equals(Double.class) || cls.equals(Long.class) || cls.equals(Float.class)) { if (data instanceof JSONArray) { JSONArray jsonData = (JSONArray) data; for (int i = 0; i < jsonData.length(); i++) { Object o = toObject(jsonData, i); invokeData.add(o); } } } else { if (data instanceof JSONArray) { JSONArray jsonData = (JSONArray) data; for (int i = 0; i < jsonData.length(); i++) { Object fObject = cls.newInstance(); JSONObject o = toJSONObject(jsonData, i); Class tmpClass = fObject.getClass(); while (tmpClass != Object.class) { Field[] fields = tmpClass.getDeclaredFields(); initParameter(o, fields, tmpClass, fObject); tmpClass = tmpClass.getSuperclass(); } invokeData.add(fObject); } } } m.invoke(source, invokeData); } else if (fClass.equals(Map.class)) { Map invokeData = new HashMap(); if (data instanceof JSONObject) { JSONObject jsonData = (JSONObject) data; for (int i = 0; i < jsonData.length(); i++) { String key = toJSONObject(jsonData, i) + ""; Object value = toJSONObject(jsonData, key); invokeData.put(key, value); } } m.invoke(source, invokeData); } else { Object invokeData = f.getType().newInstance(); Class tmpClass = invokeData.getClass(); while (tmpClass != Object.class) { Field[] fields = tmpClass.getDeclaredFields(); initParameter((JSONObject) data, fields, tmpClass, invokeData); tmpClass = tmpClass.getSuperclass(); } m.invoke(source, invokeData); } } else { if (f.getType().equals(data.getClass())) { m.invoke(source, data); } else { m.invoke(source, getParseValue(f.getType(), data)); } } } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.google.code.simplestuff.bean.SimpleBean.java
/** * //from w ww . ja va2 s . c o m * Returns a test object with all the {@link BusinessField} annotated fields * set to a test value. TODO At the moment only the String field are * considered and the collection are not considered. * * @param bean The class of the bean to fill. * @param suffix The suffix to append in the string field. * @return The bean with test values. */ public static <T> T getTestBean(Class<T> beanClass, String suffix) { if (beanClass == null) { throw new IllegalArgumentException("The bean class passed is null!!!"); } T testBean = null; try { testBean = beanClass.newInstance(); } catch (InstantiationException e1) { if (log.isDebugEnabled()) { log.debug(e1.getMessage()); } } catch (IllegalAccessException e1) { if (log.isDebugEnabled()) { log.debug(e1.getMessage()); } } BusinessObjectDescriptor businessObjectInfo = BusinessObjectContext.getBusinessObjectDescriptor(beanClass); // We don't need here a not null check since by contract the // getBusinessObjectDescriptor method always returns an abject. if (businessObjectInfo.getNearestBusinessObjectClass() != null) { Collection<Field> annotatedField = businessObjectInfo.getAnnotatedFields(); for (Field field : annotatedField) { final BusinessField fieldAnnotation = field.getAnnotation(BusinessField.class); if (fieldAnnotation != null) { try { if (field.getType().equals(String.class)) { String stringValue = "test" + StringUtils.capitalize(field.getName()) + (suffix == null ? "" : suffix); PropertyUtils.setProperty(testBean, field.getName(), stringValue); } else if ((field.getType().equals(boolean.class)) || (field.getType().equals(Boolean.class))) { PropertyUtils.setProperty(testBean, field.getName(), true); } else if ((field.getType().equals(int.class)) || (field.getType().equals(Integer.class))) { PropertyUtils.setProperty(testBean, field.getName(), 10); } else if ((field.getType().equals(char.class)) || (field.getType().equals(Character.class))) { PropertyUtils.setProperty(testBean, field.getName(), 't'); } else if ((field.getType().equals(long.class)) || (field.getType().equals(Long.class))) { PropertyUtils.setProperty(testBean, field.getName(), 10L); } else if ((field.getType().equals(float.class)) || (field.getType().equals(Float.class))) { PropertyUtils.setProperty(testBean, field.getName(), 10F); } else if ((field.getType().equals(byte.class)) || (field.getType().equals(Byte.class))) { PropertyUtils.setProperty(testBean, field.getName(), (byte) 10); } else if (field.getType().equals(Date.class)) { PropertyUtils.setProperty(testBean, field.getName(), new Date()); } else if (field.getType().equals(Collection.class)) { // TODO: create a test object of the collection // class specified (if one is specified and // recursively call this method. } } catch (IllegalAccessException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage()); } } catch (InvocationTargetException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage()); } } catch (NoSuchMethodException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage()); } } } } } return testBean; }
From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java
public static void injectCloudId(Object obj, UUID id) { for (Field f : obj.getClass().getDeclaredFields()) { if (f.getAnnotation(CloudObjectId.class) != null) { f.setAccessible(true);/*www . ja v a 2 s . c o m*/ try { if (f.getType().equals(String.class)) f.set(obj, id.toString()); else f.set(obj, id); } catch (Exception e) { e.printStackTrace(); throw new JCloudScaleException(e, "Unexpected error when injecting @CloudObjectId"); } } } }
From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java
public static void injectEventSink(Object obj) { for (Field f : obj.getClass().getDeclaredFields()) { if (f.getAnnotation(EventSink.class) != null) { f.setAccessible(true);/*from w ww .ja va 2s . c o m*/ if (IEventSink.class.isAssignableFrom(f.getType())) try { f.set(obj, new DefaultEventSink()); } catch (Exception e) { throw new JCloudScaleException(e, "Unexpected error when injecting into @EventSink"); } else throw new JCloudScaleException("Cannot inject event sink into field " + f.getName() + ". " + "Type needs to be IEventSink, but is " + f.getType().getCanonicalName()); } } }
From source file:com.ginema.api.enricher.SensitiveDataExtractor.java
/** * Recursive method to enrich the object * //from ww w. j a v a 2s . com * @param o * @param holder * @throws IllegalAccessException */ private static void enrichObjectTree(Object o, SensitiveDataHolder holder) throws Exception { for (Field f : o.getClass().getDeclaredFields()) { if (!ReflectionUtils.isPrimitive(f)) { Method getter = PropertyDescriptorHolder.getGetterMethod(o.getClass(), f.getName()); if (getter == null && !java.lang.reflect.Modifier.isStatic(f.getModifiers())) { throw new IllegalArgumentException("No getter found for property " + f.getName()); } if (getter == null) continue; Object value = getter.invoke(o, null); if (ClassUtils.isAssignable(f.getType(), SensitiveDataField.class)) { populateHolderMapByType(holder, (SensitiveDataField<?>) value); } checkAndEnrichObject(holder, value); checkAndEnrichCollection(holder, value); } } }