List of usage examples for java.lang.reflect Field getName
public String getName()
From source file:microsoft.exchange.webservices.data.core.service.schema.ServiceObjectSchema.java
/** * Adds the schema property names to dictionary. * * @param type The type. * @param propertyNameDictionary The property name dictionary. *///from w w w . j a v a 2 s . c o m protected static void addSchemaPropertyNamesToDictionary(Class<?> type, Map<PropertyDefinition, String> propertyNameDictionary) { Field[] fields = type.getDeclaredFields(); for (Field field : fields) { int modifier = field.getModifiers(); if (Modifier.isPublic(modifier) && Modifier.isStatic(modifier)) { Object o; try { o = field.get(null); if (o instanceof PropertyDefinition) { PropertyDefinition propertyDefinition = (PropertyDefinition) o; propertyNameDictionary.put(propertyDefinition, field.getName()); } } catch (IllegalArgumentException e) { LOG.error(e); // Skip the field } catch (IllegalAccessException e) { LOG.error(e); // Skip the field } } } }
From source file:fr.ign.cogit.geoxygene.datatools.ojb.GeOxygeneBrokerHelper.java
public static String buildMessageString(Object obj, Object value, Field field) { String eol = SystemUtils.LINE_SEPARATOR; StringBuffer buf = new StringBuffer(); buf.append(eol + "object class[ " //$NON-NLS-1$ + (obj != null ? obj.getClass().getName() : null)).append(eol + "target field: " //$NON-NLS-1$ + (field != null ? field.getName() : null)) .append(eol + "target field type: " //$NON-NLS-1$ + (field != null ? field.getType() : null)) .append(eol + "object value class: " //$NON-NLS-1$ + (value != null ? value.getClass().getName() : null)) .append(eol + "object value: " //$NON-NLS-1$ + (value != null ? value : null)) .append("]"); //$NON-NLS-1$ return buf.toString(); }
From source file:framework.GlobalHelpers.java
public static Field findInheritedField(Class<?> clazz, String name) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.getName().equals(name)) { return field; }/*w ww .j av a 2 s.c om*/ } if (!clazz.equals(Object.class)) { return findInheritedField(clazz.getSuperclass(), name); } return null; }
From source file:com.plusub.lib.annotate.JsonParserUtils.java
/** * ?JSONobjEntity/*from ww w . jav a2s .co m*/ * <p>Title: initEntityParser * <p>Description: * @param className ? * @param jsonString JSON * @param isParserList ?className?@JsonParserClass * @throws Exception */ public static Object initEntityParser(Class className, String jsonString, boolean isParserList) throws Exception { JSONObject jo = new JSONObject(jsonString); Object obj = getInstance(className.getName()); JsonParserClass jsonClass = obj.getClass().getAnnotation(JsonParserClass.class); String rootKey = ""; boolean isHasPage = false; String pageKey = ""; if (jsonClass != null) { rootKey = jsonClass.parserRoot(); isHasPage = jsonClass.isHasPage(); pageKey = jsonClass.pageFieldStr(); } Object result = null; if (!isParserList) { if (isEmpty(rootKey)) { result = parserField(obj, jo); } else { JSONObject json = JSONUtils.getJSONObject(jo, rootKey, null); if (json != null) { result = parserField(obj, json); } } } else { Object pageObj = null; //?page if (isHasPage) { Field field; try { field = obj.getClass().getDeclaredField(pageKey); JsonParserField jsonField = field.getAnnotation(JsonParserField.class); String key = jsonField.praserKey(); if (isEmpty(key)) { key = field.getName(); } JSONObject pageJO = JSONUtils.getJSONObject(jo, key, null); if (pageJO != null) { pageObj = getPageInfo(pageJO, field); setFieldValue(obj, field, pageObj); } } catch (NoSuchFieldException e) { // TODO Auto-generated catch block if (showLog) { Logger.e("JsonParserUtils", "Field" + pageKey); e.printStackTrace(); } } } //? JSONArray ja = JSONUtils.getJSONArray(jo, rootKey, null); if (ja != null && ja.length() > 0) { int size = ja.length(); Object[] data = new Object[size]; //? for (int index = 0; index < size; index++) { Object oj = parserField(getInstance(className.getName()), ja.getJSONObject(index)); //page? if (isHasPage && pageObj != null) { try { setFieldValue(oj, oj.getClass().getDeclaredField(pageKey), pageObj); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block if (showLog) { e.printStackTrace(); } } } data[index] = oj; } result = Arrays.asList(data); } else { if (showLog) { Logger.i(TAG, "JSONArray is Empty " + rootKey); } } } return result; }
From source file:com.google.code.simplestuff.bean.SimpleBean.java
/** * /* www. ja va 2 s . co 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:com.tugo.dt.PojoUtils.java
/** * Return the getter expression for the given field. * <p>/*from ww w.jav a2 s . c o m*/ * If the field is a public member, the field name is used else the getter function. If no matching field or getter * method is found, the expression is returned unmodified. * * @param pojoClass class to check for the field * @param fieldExpression field name expression * @param exprClass expected field type * @return java code fragment */ private static String getSingleFieldGetterExpression(final Class<?> pojoClass, final String fieldExpression, final Class<?> exprClass) { JavaStatement code = new JavaReturnStatement( pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32, exprClass); code.appendCastToTypeExpr(pojoClass, OBJECT).append("."); try { final Field field = pojoClass.getField(fieldExpression); if (ClassUtils.isAssignable(field.getType(), exprClass)) { return code.append(field.getName()).getStatement(); } logger.debug("Field {} can not be assigned to an {}. Proceeding to locate a getter method.", field, exprClass); } catch (NoSuchFieldException ex) { logger.debug("{} does not have field {}. Proceeding to locate a getter method.", pojoClass, fieldExpression); } catch (SecurityException ex) { logger.debug("{} does not have field {}. Proceeding to locate a getter method.", pojoClass, fieldExpression); } String methodName = GET + upperCaseWord(fieldExpression); try { Method method = pojoClass.getMethod(methodName); if (ClassUtils.isAssignable(method.getReturnType(), exprClass)) { return code.append(methodName).append("()").getStatement(); } logger.debug( "method {} of the {} returns {} that can not be assigned to an {}. Proceeding to locate another getter method.", pojoClass, methodName, method.getReturnType(), exprClass); } catch (NoSuchMethodException ex) { logger.debug("{} does not have method {}. Proceeding to locate another getter method.", pojoClass, methodName); } catch (SecurityException ex) { logger.debug("{} does not have method {}. Proceeding to locate another getter method.", pojoClass, methodName); } methodName = IS + upperCaseWord(fieldExpression); try { Method method = pojoClass.getMethod(methodName); if (ClassUtils.isAssignable(method.getReturnType(), exprClass)) { return code.append(methodName).append("()").getStatement(); } logger.debug( "method {} of the {} returns {} that can not be assigned to an {}. Proceeding with the original expression {}.", pojoClass, methodName, method.getReturnType(), exprClass, fieldExpression); } catch (NoSuchMethodException ex) { logger.debug("{} does not have method {}. Proceeding with the original expression {}.", pojoClass, methodName, fieldExpression); } catch (SecurityException ex) { logger.debug("{} does not have method {}. Proceeding with the original expression {}.", pojoClass, methodName, fieldExpression); } return code.append(fieldExpression).getStatement(); }
From source file:eu.crisis_economics.abm.model.ModelUtils.java
private static ConfigurationModifier findGetterSetterMethods(final Field field, final Object classInstance, final String parameterID) throws SecurityException, NoSuchMethodException { final Class<?> type = classInstance.getClass(); final String fieldName = field.getName(), expectedGetterName = "get" + WordUtils.capitalize(fieldName), expectedSetterName = "set" + WordUtils.capitalize(fieldName); final Method getterMethod = type.getMethod(expectedGetterName), setterMethod = type.getMethod(expectedSetterName, field.getType()); return new ConfigurationModifier(field, getterMethod, setterMethod, classInstance, parameterID); }
From source file:ambroafb.general.AnnotiationUtils.java
private static boolean checkValidationForContentMailAnnotation(Field field, Object currSceneController) { boolean contentIsCorrect = false; Annotations.ContentMail annotation = field.getAnnotation(Annotations.ContentMail.class); Object[] typeAndContent = getNodesTypeAndContent(field, currSceneController); boolean validSyntax = Pattern.matches(annotation.valueForSyntax(), (String) typeAndContent[1]); boolean validAlphabet = Pattern.matches(annotation.valueForAlphabet(), (String) typeAndContent[1]); boolean predicateValue = getPredicateValue(annotation.predicate(), field.getName()); if (predicateValue && !validSyntax) { // otherwise email check label may stay a red color changeNodeTitleLabelVisual((Node) typeAndContent[0], annotation.explainForSyntax()); } else if (predicateValue && !validAlphabet) { // otherwise email check label may stay a red color changeNodeTitleLabelVisual((Node) typeAndContent[0], annotation.explainForAlphabet()); } else {/* w w w. j ava2s . c om*/ changeNodeTitleLabelVisual((Node) typeAndContent[0], ""); contentIsCorrect = true; } return contentIsCorrect; }
From source file:com.lonepulse.zombielink.proxy.Zombie.java
/** * <p>Accepts an object and scans it for {@link Bite} annotations. If found, a <b>thread-safe proxy</b> * for the endpoint interface will be injected.</p> * /* w w w. j a va 2s . c o m*/ * <p>Injection targets will be searched up an inheritance hierarchy until a type is found which is * <b>not</b> in a package whose name starts with the given package prefixes.</p> * <br> * <b>Usage:</b> * <br><br> * <ul> * <li> * <h5>Property Injection</h5> * <pre> * <code><b>@Bite</b> * private GitHubEndpoint gitHubEndpoint; * { * Zombie.infect(Arrays.asList("com.example.service", "com.example.manager"), this); * } * </code> * </pre> * </li> * <li> * <h5>Setter Injection</h5> * <pre> * <code><b>@Bite</b> * private GitHubEndpoint gitHubEndpoint; * { * Zombie.infect(Arrays.asList("com.example.service", "com.example.manager"), this); * } * </code> * <code> * public void setGitHubEndpoint(GitHubEndpoint gitHubEndpoint) { * * this.gitHubEndpoint = gitHubEndpoint; * } * </code> * </pre> * </li> * </ul> * * @param packagePrefixes * the prefixes of packages to restrict hierarchical lookup of injection targets; if {@code null} * or {@code empty}, {@link #infect(Object, Object...)} will be used * <br><br> * @param victim * an object with endpoint references marked to be <i>bitten</i> and infected * <br><br> * @param moreVictims * more unsuspecting objects with endpoint references to be infected * <br><br> * @throws NullPointerException * if the object supplied for endpoint injection is {@code null} * <br><br> * @since 1.3.0 */ public static void infect(List<String> packagePrefixes, Object victim, Object... moreVictims) { assertNotNull(victim); List<Object> injectees = new ArrayList<Object>(); injectees.add(victim); if (moreVictims != null && moreVictims.length > 0) { injectees.addAll(Arrays.asList(moreVictims)); } Class<?> endpointInterface = null; for (Object injectee : injectees) { Class<?> type = injectee.getClass(); do { for (Field field : Fields.in(type).annotatedWith(Bite.class)) { try { endpointInterface = field.getType(); Object proxyInstance = EndpointProxyFactory.INSTANCE.create(endpointInterface); try { //1.Simple Field Injection field.set(injectee, proxyInstance); } catch (IllegalAccessException iae) { //2.Setter Injection String fieldName = field.getName(); String mutatorName = "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); try { Method mutator = injectee.getClass().getDeclaredMethod(mutatorName, endpointInterface); mutator.invoke(injectee, proxyInstance); } catch (NoSuchMethodException nsme) { //3.Forced Field Injection field.setAccessible(true); field.set(injectee, proxyInstance); } } } catch (Exception e) { Logger.getLogger(Zombie.class.getName()).log(Level.SEVERE, new StringBuilder().append("Failed to inject the endpoint proxy instance of type ") .append(endpointInterface.getName()).append(" on property ") .append(field.getName()).append(" at ") .append(injectee.getClass().getName()).append(". ").toString(), e); } } type = type.getSuperclass(); } while (!hierarchyTerminal(type, packagePrefixes)); } }
From source file:adalid.core.XS1.java
private static Collection<Field> getRidOfDupFields(Collection<Field> fields) { LinkedHashMap<String, Field> map = new LinkedHashMap<>(); String key;//w ww . ja va 2 s .c o m for (Field field : fields) { key = field.getName(); if (map.containsKey(key)) { TLC.getProject().getParser().error("Field " + key + " hides another field"); logger.error(TAB + "hiding field: " + field); logger.error(TAB + "hidden field: " + map.get(key)); } map.put(key, field); } return map.values(); }