List of usage examples for java.lang.reflect Field getDeclaredAnnotations
public Annotation[] getDeclaredAnnotations()
From source file:Spy.java
public static void main(String... args) throws Exception { Class<?> c = Class.forName("Spy"); Field[] flds = c.getFields(); for (Field f : flds) { Annotation[] annos = f.getDeclaredAnnotations(); for (Annotation anno : annos) { System.out.println(anno.toString()); }/* w w w .ja v a 2s.c om*/ } }
From source file:Main.java
public static Field findFieldWithAnntationAndValue(Field[] fields, String annClassName, String key, String value) {//from w w w. j a v a2 s . c om if (fields == null) { return null; } for (Field field : fields) { Annotation[] annotations = field.getDeclaredAnnotations(); String ret = getValueInAnntationList(annotations, annClassName, key); if (ret.equals(value)) { return field; } } return null; }
From source file:Main.java
public static String getValueByFieldAnntation(Field field, String annClassName, String key) { Annotation[] annotations = field.getDeclaredAnnotations(); return getValueInAnntationList(annotations, annClassName, key); }
From source file:com.vmware.photon.controller.common.dcp.validation.NotBlankValidator.java
public static void validate(ServiceDocument state) { try {//from www. j a va 2s .c om Field[] declaredFields = state.getClass().getDeclaredFields(); for (Field field : declaredFields) { Annotation[] declaredAnnotations = field.getDeclaredAnnotations(); for (Annotation annotation : declaredAnnotations) { if (annotation.annotationType() == NotBlank.class) { checkState(null != field.get(state), String.format("%s cannot be null", field.getName())); if (String.class.equals(field.getType())) { checkState((StringUtils.isNotBlank((String) field.get(state))), String.format("%s cannot be blank", field.getName())); } } } } } catch (IllegalStateException e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } }
From source file:Main.java
public static Map<String, Object> convertObjToMap(Object object, String token) { Map<String, Object> map = new HashMap<>(); if (object == null) { return null; }//from ww w. j a v a 2 s . c om Field[] fields = object.getClass().getSuperclass().getDeclaredFields(); Field[] ff = object.getClass().getDeclaredFields(); try { for (int i = 0; i < fields.length; i++) { Field field = object.getClass().getSuperclass().getDeclaredField(fields[i].getName()); field.setAccessible(true); Annotation[] annotations = field.getDeclaredAnnotations(); String key = ""; for (Annotation annotation : annotations) { if (annotation instanceof SerializedName) { key = ((SerializedName) annotation).value(); } } if (TextUtils.isEmpty(key)) { key = fields[i].getName(); } Object o = field.get(object); map.put(key, o); } for (int i = 0; i < ff.length; i++) { Field field = object.getClass().getDeclaredField(ff[i].getName()); field.setAccessible(true); Annotation[] annotations = field.getDeclaredAnnotations(); String key = ""; for (Annotation annotation : annotations) { if (annotation instanceof SerializedName) { key = ((SerializedName) annotation).value(); } } if (TextUtils.isEmpty(key)) { key = ff[i].getName(); } Object o = field.get(object); map.put(key, o); } } catch (Exception e) { e.printStackTrace(); } map.remove("token"); map.put("token", token); Log.d(".......", "convert success"); return map; }
From source file:ee.ria.xroad.common.message.SoapUtils.java
/** * Returns the XmlElement annotation for the given field, if the annotation * exists. Returns null, if field has no such annotation. * @param field the field from which to get the XmlElement annotation * @return the XmlElement annotation/*from w ww .ja v a 2s.c o m*/ */ public static XmlElement getXmlElementAnnotation(Field field) { for (Annotation annotation : field.getDeclaredAnnotations()) { if (annotation instanceof XmlElement) { return (XmlElement) annotation; } } return null; }
From source file:org.openlegacy.db.mvc.rest.DefaultDbRestController.java
private static Class<?> getFirstIdJavaType(Class<?> entityClass) { for (Field field : entityClass.getDeclaredFields()) { Annotation[] annotations = field.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation.annotationType().equals(javax.persistence.Id.class)) { return field.getType(); }/*from w w w. j a v a2 s. c o m*/ } } return null; }
From source file:com.ocs.dynamo.utils.ClassUtils.java
/** * Returns an annotation on a certain field * /* w ww .ja v a 2 s .c o m*/ * @param field * the field * @param annotationClass * the annotation class * @return */ @SuppressWarnings("unchecked") public static <T extends Annotation> T getAnnotationOnField(Field field, Class<T> annotationClass) { T result = null; if (field != null) { for (Annotation a : field.getDeclaredAnnotations()) { if (a.annotationType().equals(annotationClass)) { result = (T) a; } } } return result; }
From source file:com.espertech.esper.util.PopulateUtil.java
public static void populateObject(String operatorName, int operatorNum, String dataFlowName, Map<String, Object> objectProperties, Object top, EngineImportService engineImportService, EPDataFlowOperatorParameterProvider optionalParameterProvider, Map<String, Object> optionalParameterURIs) throws ExprValidationException { Class applicableClass = top.getClass(); Set<WriteablePropertyDescriptor> writables = PropertyHelper.getWritableProperties(applicableClass); Set<Field> annotatedFields = JavaClassHelper.findAnnotatedFields(top.getClass(), DataFlowOpParameter.class); Set<Method> annotatedMethods = JavaClassHelper.findAnnotatedMethods(top.getClass(), DataFlowOpParameter.class); // find catch-all methods Set<Method> catchAllMethods = new LinkedHashSet<Method>(); if (annotatedMethods != null) { for (Method method : annotatedMethods) { DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper .getAnnotations(DataFlowOpParameter.class, method.getDeclaredAnnotations()).get(0); if (anno.all()) { if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == String.class && method.getParameterTypes()[1] == Object.class) { catchAllMethods.add(method); continue; }/*from ww w . j a v a2 s . c om*/ throw new ExprValidationException("Invalid annotation for catch-call"); } } } // map provided values for (Map.Entry<String, Object> property : objectProperties.entrySet()) { boolean found = false; String propertyName = property.getKey(); // invoke catch-all setters for (Method method : catchAllMethods) { try { method.invoke(top, new Object[] { propertyName, property.getValue() }); } catch (IllegalAccessException e) { throw new ExprValidationException("Illegal access invoking method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + method.getName(), e); } catch (InvocationTargetException e) { throw new ExprValidationException("Exception invoking method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + method.getName() + ": " + e.getTargetException().getMessage(), e); } found = true; } if (propertyName.toLowerCase().equals(CLASS_PROPERTY_NAME)) { continue; } // use the writeable property descriptor (appropriate setter method) from writing the property WriteablePropertyDescriptor descriptor = findDescriptor(applicableClass, propertyName, writables); if (descriptor != null) { Object coerceProperty = coerceProperty(propertyName, applicableClass, property.getValue(), descriptor.getType(), engineImportService, false); try { descriptor.getWriteMethod().invoke(top, new Object[] { coerceProperty }); } catch (IllegalArgumentException e) { throw new ExprValidationException("Illegal argument invoking setter method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + descriptor.getWriteMethod().getName() + " provided value " + coerceProperty, e); } catch (IllegalAccessException e) { throw new ExprValidationException("Illegal access invoking setter method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + descriptor.getWriteMethod().getName(), e); } catch (InvocationTargetException e) { throw new ExprValidationException("Exception invoking setter method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + descriptor.getWriteMethod().getName() + ": " + e.getTargetException().getMessage(), e); } continue; } // find the field annotated with {@link @GraphOpProperty} for (Field annotatedField : annotatedFields) { DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper .getAnnotations(DataFlowOpParameter.class, annotatedField.getDeclaredAnnotations()).get(0); if (anno.name().equals(propertyName) || annotatedField.getName().equals(propertyName)) { Object coerceProperty = coerceProperty(propertyName, applicableClass, property.getValue(), annotatedField.getType(), engineImportService, true); try { annotatedField.setAccessible(true); annotatedField.set(top, coerceProperty); } catch (Exception e) { throw new ExprValidationException( "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e); } found = true; break; } } if (found) { continue; } throw new ExprValidationException("Failed to find writable property '" + propertyName + "' for class " + applicableClass.getName()); } // second pass: if a parameter URI - value pairs were provided, check that if (optionalParameterURIs != null) { for (Field annotatedField : annotatedFields) { try { annotatedField.setAccessible(true); String uri = operatorName + "/" + annotatedField.getName(); if (optionalParameterURIs.containsKey(uri)) { Object value = optionalParameterURIs.get(uri); annotatedField.set(top, value); if (log.isDebugEnabled()) { log.debug("Found parameter '" + uri + "' for data flow " + dataFlowName + " setting " + value); } } else { if (log.isDebugEnabled()) { log.debug("Not found parameter '" + uri + "' for data flow " + dataFlowName); } } } catch (Exception e) { throw new ExprValidationException( "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e); } } for (Method method : annotatedMethods) { DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper .getAnnotations(DataFlowOpParameter.class, method.getDeclaredAnnotations()).get(0); if (anno.all()) { if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == String.class && method.getParameterTypes()[1] == Object.class) { for (Map.Entry<String, Object> entry : optionalParameterURIs.entrySet()) { String[] elements = URIUtil.parsePathElements(URI.create(entry.getKey())); if (elements.length < 2) { throw new ExprValidationException("Failed to parse URI '" + entry.getKey() + "', expected " + "'operator_name/property_name' format"); } if (elements[0].equals(operatorName)) { try { method.invoke(top, new Object[] { elements[1], entry.getValue() }); } catch (IllegalAccessException e) { throw new ExprValidationException( "Illegal access invoking method for property '" + entry.getKey() + "' for class " + applicableClass.getName() + " method " + method.getName(), e); } catch (InvocationTargetException e) { throw new ExprValidationException( "Exception invoking method for property '" + entry.getKey() + "' for class " + applicableClass.getName() + " method " + method.getName() + ": " + e.getTargetException().getMessage(), e); } } } } } } } // third pass: if a parameter provider is provided, use that if (optionalParameterProvider != null) { for (Field annotatedField : annotatedFields) { try { annotatedField.setAccessible(true); Object provided = annotatedField.get(top); Object value = optionalParameterProvider.provide(new EPDataFlowOperatorParameterProviderContext( operatorName, annotatedField.getName(), top, operatorNum, provided, dataFlowName)); if (value != null) { annotatedField.set(top, value); } } catch (Exception e) { throw new ExprValidationException( "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e); } } } }
From source file:ro.allevo.fintpws.test.TestUtils.java
/** * Method fillResourceData.// w ww . j a v a 2 s .c o m * * @param entityObject * JSONObject * @param entity * Object * @return JSONObject */ public static JSONObject fillResourceData(JSONObject entityObject, Object entity) { String fieldName = ""; boolean isTransient = false; int columnSize = 0; Field field = null; boolean haveAnnotation = false; final Method[] allMethods = entity.getClass().getDeclaredMethods(); for (Method classMethod : allMethods) { if (classMethod.getName().startsWith("set")) { isTransient = false; columnSize = 0; haveAnnotation = false; fieldName = classMethod.getName().substring(3).toLowerCase(); try { field = entity.getClass().getDeclaredField(fieldName); Annotation[] annotations = field.getDeclaredAnnotations(); for (Annotation ant : annotations) { isTransient = ant.toString().contains("Transient"); columnSize = getColumnSize(ant.toString()); haveAnnotation = true; } if (!isTransient || !haveAnnotation) { if (field.getType().toString().contains("BigDecimal") || field.getType().toString().contains("long")) { entityObject.put(fieldName, new Random().nextInt((int) Math.pow(10, columnSize))); } else { if (field.getType().toString().contains("Timestamp")) { entityObject.put(fieldName, new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .format(Calendar.getInstance().getTime())); } else { final String randomVarchar = RandomStringUtils.randomAlphanumeric(columnSize); entityObject.put(fieldName, randomVarchar); } } } } catch (SecurityException e) { logger.error("reflectin security exception"); } catch (NoSuchFieldException e) { logger.error("reflection field exception"); } catch (JSONException e) { logger.error("reflection json exception"); } } } return entityObject; }