Java Code Examples for java.lang.reflect.Field#isAnnotationPresent()

The following examples show how to use java.lang.reflect.Field#isAnnotationPresent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DynamoDBMappingContext.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean shouldCreatePersistentEntityFor(TypeInformation<?> type) {

	boolean hasHashKey = false;
	boolean hasRangeKey = false;
	for (Method method : type.getType().getMethods()) {
		if (method.isAnnotationPresent(DynamoDBHashKey.class))
			hasHashKey = true;
		if (method.isAnnotationPresent(DynamoDBRangeKey.class))
			hasRangeKey = true;

	}
	for (Field field : type.getType().getFields()) {
		if (field.isAnnotationPresent(DynamoDBHashKey.class))
			hasHashKey = true;
		if (field.isAnnotationPresent(DynamoDBRangeKey.class))
			hasRangeKey = true;

	}
	return type.getType().isAnnotationPresent(DynamoDBTable.class) || (hasHashKey && hasRangeKey);
}
 
Example 2
Source File: MessageDataUtils.java    From DeskChan with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Entry extractField(Field field, Object owner){
    field.setAccessible(true);
	if (Modifier.isStatic(field.getModifiers())) {
		return null;
	}
	if (field.isAnnotationPresent(MessageData.Ignore.class)) {
		return null;
	}
	MessageData.FieldName fieldNameAnnotation = field.getAnnotation(MessageData.FieldName.class);
	String fieldName = fieldNameAnnotation != null ? fieldNameAnnotation.value() : field.getName();
	try {
		Object fieldValue = field.get(owner);
		if (fieldValue != null)
			return new Entry(fieldName, serialize(fieldValue));
	} catch (Exception e) {
		//System.out.println(e.getClass().getSimpleName() + " " + e.getMessage());
	}
	return null;
}
 
Example 3
Source File: BeanValidatorBuilder.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
private boolean hasValidationAnnotation(Field field) {
    boolean hasAnnotation = field.isAnnotationPresent(NotNull.class)
            || field.isAnnotationPresent(NotBlank.class)
            || field.isAnnotationPresent(Max.class)
            || field.isAnnotationPresent(Min.class)
            || field.isAnnotationPresent(Pattern.class)
            || field.isAnnotationPresent(Size.class);
    if (hasAnnotation) return true;

    Class<?> targetClass = targetValidationClass(field);
    if (!isValueClass(targetClass)) {
        for (Field valueField : Classes.instanceFields(targetClass)) {
            if (hasValidationAnnotation(valueField)) return true;
        }
    }
    return false;
}
 
Example 4
Source File: ActionPlugins.java    From hawkular-alerts with Apache License 2.0 6 votes vote down vote up
private void injectActionPluginSender(String actionPlugin, ActionPluginListener pluginInstance) throws Exception {
    if (pluginInstance == null) {
        throw new IllegalArgumentException("pluginInstance must be not null");
    }
    Field[] fields = pluginInstance.getClass().getDeclaredFields();
    Field sender = null;
    for (Field field : fields) {
        if (field.isAnnotationPresent(Sender.class) &&
                field.getType().isAssignableFrom(ActionPluginSender.class)) {
            sender = field;
            break;
        }
    }
    if (sender != null) {
        ActionPluginSender standaloneSender = new StandaloneActionPluginSender(actions);
        sender.setAccessible(true);
        sender.set(pluginInstance, standaloneSender);
        senders.put(actionPlugin, standaloneSender);
    }
}
 
Example 5
Source File: ReflectionTableParser.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private Map<String, ColumnDefinition> getColumnDefinitionsFromFields(Object object) {
    Class<?> clazz = object.getClass();
    if (Objects.isNull(AnnotationUtils.findAnnotation(clazz, textTableClass))) {
        return Collections.emptyMap();
    }

    Map<String, ColumnDefinition> columnDefinitions = new LinkedHashMap<>();
    for (Field field : object.getClass().getDeclaredFields()) {
        if (field.isAnnotationPresent(textColumnClass)) {
            TextColumn textColumn = field.getAnnotation(textColumnClass);
            String columnKey = StringUtils.defaultIfEmpty(textColumn.key(), field.getName());
            columnDefinitions.put(columnKey, getColumnDefinition(textColumn, field));
        }
    }

    return columnDefinitions;
}
 
Example 6
Source File: DataAccessFieldCallback.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
    if (!field.isAnnotationPresent(DataAccess.class)) {
        return;
    }
    ReflectionUtils.makeAccessible(field);
    final Type fieldGenericType = field.getGenericType();
    // In this example, get actual "GenericDAO' type.
    final Class<?> generic = field.getType();
    final Class<?> classValue = field.getDeclaredAnnotation(DataAccess.class).entity();

    if (genericTypeIsValid(classValue, fieldGenericType)) {
        final String beanName = classValue.getSimpleName() + generic.getSimpleName();
        final Object beanInstance = getBeanInstance(beanName, generic, classValue);
        field.set(bean, beanInstance);
    } else {
        throw new IllegalArgumentException(ERROR_ENTITY_VALUE_NOT_SAME);
    }
}
 
Example 7
Source File: HealthStatsMetrics.java    From Battery-Metrics with MIT License 5 votes vote down vote up
private static void readKeyNames() {
  try {
    Class[] healthStatsClasses = {
      UidHealthStats.class,
      PidHealthStats.class,
      ProcessHealthStats.class,
      PackageHealthStats.class,
      ServiceHealthStats.class
    };
    Class annotationClass = Class.forName("android.os.health.HealthKeys$Constant");
    for (Class clazz : healthStatsClasses) {
      Field[] fields = clazz.getFields();
      for (Field field : fields) {
        if (field.isAnnotationPresent(annotationClass)) {
          sKeyNames.put(field.getInt(null), field.getName());
        }
      }
    }
    return;
  } catch (IllegalAccessException iae) {
    SystemMetricsLogger.wtf(TAG, "Unable to read constant names", iae);
  } catch (ClassNotFoundException cnfe) {
    SystemMetricsLogger.wtf(TAG, "Unable to find constant annotation", cnfe);
  }

  // Mark as attempted and invalid
  sKeyNames.put(-1, "Unable to read");
}
 
Example 8
Source File: HtmlParser.java    From gecco with MIT License 5 votes vote down vote up
public Object $basic(String selector, Field field) throws Exception {
	if (field.isAnnotationPresent(Text.class)) {// @Text
		Text text = field.getAnnotation(Text.class);
		String value = $text(selector, text.own());
		return Conversion.getValue(field.getType(), value);
	} else if (field.isAnnotationPresent(Image.class)) {// @Image
		Image image = field.getAnnotation(Image.class);
		String imageSrc = $image(selector, image.value());
		/*String localPath = DownloadImage.download(image.download(), imageSrc);
		if (StringUtils.isNotEmpty(localPath)) {
			return localPath;
		}*/
		return imageSrc;
	} else if (field.isAnnotationPresent(Href.class)) {// @Href
		Href href = field.getAnnotation(Href.class);
		String url = $href(selector, href.value());
		return url;
	} else if (field.isAnnotationPresent(Attr.class)) {// @Attr
		Attr attr = field.getAnnotation(Attr.class);
		String name = attr.value();
		return Conversion.getValue(field.getType(), $attr(selector, name));
	} else if (field.isAnnotationPresent(Html.class)) {// @Html
		Html html = field.getAnnotation(Html.class);
		return $html(selector, html.outer());
	} else {// @Html
		return $html(selector);
	}
}
 
Example 9
Source File: Validatable.java    From fluency with Apache License 2.0 5 votes vote down vote up
default void validate()
{
    Class<? extends Object> klass = getClass();
    while (klass != Object.class) {
        for (Field field : klass.getDeclaredFields()) {
            for (ValidationList.Validation validation : ValidationList.VALIDATIONS) {
                Class<? extends Annotation> annotationClass = validation.annotationClass;
                if (field.isAnnotationPresent(annotationClass)) {
                    Annotation annotation = field.getAnnotation(annotationClass);
                    Object value;
                    try {
                        field.setAccessible(true);
                        value = field.get(this);
                    }
                    catch (IllegalAccessException e) {
                        throw new RuntimeException(
                                String.format("Failed to get a value from field (%s)", field), e);
                    }

                    if (value == null) {
                        break;
                    }

                    if (!(value instanceof Number)) {
                        throw new IllegalArgumentException(
                                String.format("This field has (%s), but actual field is (%s)", annotation, value.getClass()));
                    }

                    if (!validation.isValid.apply(annotation, (Number) value)) {
                        throw new IllegalArgumentException(
                                String.format(validation.messageTemplate, field, value));
                    }
                }
            }
        }
        klass = klass.getSuperclass();
    }
}
 
Example 10
Source File: SignUtils.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
/**
 * 将bean按照@XStreamAlias标识的字符串内容生成以之为key的map对象
 *
 * @param bean 包含@XStreamAlias的xml bean对象
 * @return map对象
 */
public static Map<String, String> xmlBean2Map(Object bean) {
  Map<String, String> result = Maps.newHashMap();
  List<Field> fields = new ArrayList<>(Arrays.asList(bean.getClass().getDeclaredFields()));
  fields.addAll(Arrays.asList(bean.getClass().getSuperclass().getDeclaredFields()));
  if(bean.getClass().getSuperclass().getSuperclass() == BaseWxPayRequest.class){
    fields.addAll(Arrays.asList(BaseWxPayRequest.class.getDeclaredFields()));
  }

  if(bean.getClass().getSuperclass().getSuperclass() == BaseWxPayResult.class){
    fields.addAll(Arrays.asList(BaseWxPayResult.class.getDeclaredFields()));
  }

  for (Field field : fields) {
    try {
      boolean isAccessible = field.isAccessible();
      field.setAccessible(true);
      if (field.get(bean) == null) {
        field.setAccessible(isAccessible);
        continue;
      }

      if (field.isAnnotationPresent(XStreamAlias.class)) {
        result.put(field.getAnnotation(XStreamAlias.class).value(), field.get(bean).toString());
      } else if (!Modifier.isStatic(field.getModifiers())) {
        //忽略掉静态成员变量
        result.put(field.getName(), field.get(bean).toString());
      }

      field.setAccessible(isAccessible);
    } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
      log.error(e.getMessage(), e);
    }

  }

  return result;
}
 
Example 11
Source File: ReflectionUtils.java    From jkes with Apache License 2.0 5 votes vote down vote up
/**
 * Get annotated field. The field can be in parent field
 *
 * @param clazz clazz
 * @param fieldName fieldName
 * @param annotation annotation
 * @return annotated field.
 */
public static Field getAnnotatedField(Class<?> clazz, String fieldName, Class<? extends Annotation> annotation) {
    do {
        Field[] fields = clazz.getDeclaredFields();
        for(Field field : fields) {
            if(Objects.equals(fieldName, field.getName()) && field.isAnnotationPresent(annotation)) {
                return field;
            }
        }

        clazz = clazz.getSuperclass();
    }while (clazz != null);

    return null;
}
 
Example 12
Source File: DOMFactory.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generates an xml element from this pojo. Translating the fields like described
 * in the class description.
 * @param document The document in which the nodes should be.
 * @param rootName This is to use another name for the root element than the
 * simple class name.
 * @param pojo The pojo to take the fields from.
 * @param attributes The fields which should be used as attributes and not
 * as elements.
 * @return The create element representing the provided pojo.
 * @throws ParserConfigurationException Might throw a ParserConfigurationException.
 * @throws IllegalAccessException Might throw a IllegalAccessException.
 * @throws InstantiationException Might throw a InstantiationException.
 */
public Element generateSimpleElement(final Document document, final String rootName,
        final Object pojo, final List<String> attributes) 
        throws ParserConfigurationException,
        IllegalAccessException, InstantiationException {
    Element rootNode = document.createElementNS(getDefaultNamespace(), rootName);
    List<Field> fields = getNonTransientSimpleFields(pojo.getClass());
    for (Field field : fields) {            
        field.setAccessible(true);
        String fieldName = field.getName();
                                
        if (field.get(pojo) != null) {
            
            if (!attributes.contains(fieldName)) {
                
                Element element = document.createElementNS(getDefaultNamespace(), getElementName(field));
                
                // handle CDATAs
                if (field.isAnnotationPresent(XmlValue.class)) {
                    CDATASection cdata = document.createCDATASection(field.get(pojo).toString());
                    element.appendChild(cdata);
                }
                else {
                  element.setTextContent(field.get(pojo).toString());                    
                }
                
                rootNode.appendChild(element);                    
            }
            else {
                rootNode.setAttribute(getAttributeName(field), field.get(pojo).toString());
            }
        }
    }
    return rootNode;
}
 
Example 13
Source File: StringFieldMapper.java    From elasticsearch-mapper with Apache License 2.0 5 votes vote down vote up
public static void mapDataType(XContentBuilder mappingBuilder, Field field) throws IOException {
    if (!isValidStringFieldType(field)) {
        throw new IllegalArgumentException(
                String.format("field type[%s] is invalid type of string.", field.getType()));
    }

    if (field.isAnnotationPresent(StringField.class)) {
        StringField stringField = field.getDeclaredAnnotation(StringField.class);
        mapDataType(mappingBuilder, stringField);

        return;
    }

    mappingBuilder.field("type", "keyword");
}
 
Example 14
Source File: TableCreateStatement.java    From Storm with Apache License 2.0 4 votes vote down vote up
private boolean isUnique(Field field) {
    return field.isAnnotationPresent(UNIQUE_CLASS);
}
 
Example 15
Source File: ModelSupport.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private static boolean isChoice(Field field) {
    return field.isAnnotationPresent(Choice.class);
}
 
Example 16
Source File: TechContext.java    From jeddict with Apache License 2.0 4 votes vote down vote up
public LayerConfigPanel createPanel(Project project, SourceGroup sourceGroup, String _package) {
    if (panel == null) {
        if (isValid()) {
            try {
                panel = getTechnology().panel().newInstance();
            } catch (InstantiationException | IllegalAccessException ex) {
                Exceptions.printStackTrace(ex);
            }
        } else {
            panel = new DefaultConfigPanel();
        }
        
        Class<LayerConfigData> configDataClass = panel.getConfigDataClass();
        panel.setConfigData(PreferenceUtils.get(project, configDataClass));
        
        Map<Class<? extends LayerConfigPanel>, LayerConfigPanel> siblingData = new HashMap<>();
        Map<Class<? extends LayerConfigPanel>, LayerConfigPanel> cacheSiblingData = new HashMap<>();
        for(TechContext siblingContext : getSiblingTechContext()){
           LayerConfigPanel siblingPanel = siblingContext.createPanel(project, sourceGroup, _package);
           siblingData.put(siblingPanel.getClass(), siblingPanel);
        }
        
        cacheSiblingData.putAll(siblingData);
        cacheSiblingData.put(panel.getClass(), panel);
        Iterator<Entry<Class<? extends LayerConfigPanel>, LayerConfigPanel>> iterator = siblingData.entrySet().iterator();
        while(iterator.hasNext()){
            Entry<Class<? extends LayerConfigPanel>, LayerConfigPanel> entry = iterator.next();
            LayerConfigPanel instance = entry.getValue();
            List<Field> fields = Arrays.asList(instance.getClass().getDeclaredFields());
            for (Field field : fields) {
                if (field.isAnnotationPresent(ConfigData.class)) {
                    field.setAccessible(true);
                    try {
                        if (LayerConfigPanel.class.isAssignableFrom(field.getType())) {
                            field.set(instance, cacheSiblingData.get(field.getType()));
                        }
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
            instance.init(_package, project, sourceGroup);
            instance.read();
        }
           
        if (parentTechContext == null) { //if sibling context then first inject field and then init
            panel.init(_package, project, sourceGroup);
            panel.read();
        }
    }
    return panel;
}
 
Example 17
Source File: ClassUtils.java    From minnal with Apache License 2.0 4 votes vote down vote up
public static boolean hasAnnotation(Field field, Class<? extends Annotation> clazz) {
	return field.isAnnotationPresent(clazz);
}
 
Example 18
Source File: EntityDecoderBuilder.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
private String mongoField(Field field) {
    if (field.isAnnotationPresent(Id.class)) return "_id";
    return field.getDeclaredAnnotation(core.framework.mongo.Field.class).name();
}
 
Example 19
Source File: RESTApiJsonTemplateGenerator.java    From zstack with Apache License 2.0 4 votes vote down vote up
private static JSONObject dumpObject(Class<?> clazz, Stack<Class> hasDone) throws JSONException {
    JSONObject jo = nj();
    if (hasDone.contains(clazz)) {
        jo.put("refer to", clazz.getName());
        return jo;
    }

    hasDone.push(clazz);

    logger.debug(String.format("dumping object: %s", clazz.getName()));
    do {
        Field[] fields = clazz.getDeclaredFields();
        for (Field f : fields) {
            if (f.isAnnotationPresent(APINoSee.class)) {
                continue;
            }
            if (Modifier.isStatic(f.getModifiers())) {
                continue;
            }

            Class ct = f.getType();
            Type t = f.getGenericType();
            if (ct.equals(clazz)) {
                jo.put(f.getName(), "refer to self");
            } else if (t instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) t;
                if (Collection.class.isAssignableFrom(ct)) {
                    JSONArray arr = dumpCollection(pt, hasDone);
                    jo.put(f.getName(), arr);
                } else if (Map.class.isAssignableFrom(ct)) {
                    Class<?> keyType = (Class<?>) pt.getActualTypeArguments()[0];
                    if (!String.class.isAssignableFrom(keyType)) {
                        throw new IllegalArgumentException(String.format(
                                "Field[%s] of class[%s] is type of Map, but type[%s] of its key element is not String, unable to dump", f.getName(),
                                clazz.getName(), keyType));
                    }
                    JSONObject mj = dumpMap(pt, hasDone);
                    jo.put(f.getName(), mj);
                } else {
                    throw new IllegalArgumentException(String.format(
                            "Field[%s] of class[%s] is type of java generic type[%s], but it's not Collection or Map, unable to dump", f.getName(),
                            clazz.getName(), pt.getRawType()));
                }
            } else {
                if (isPrimitiveType(ct)) {
                    jo.put(f.getName(), populateTemplateString(f));
                } else if (Collection.class.isAssignableFrom(ct)) {
                    logger.warn(String.format(
                            "Field[%s] of class[%s] is type of Collection, unable to dump it because it doesn't have java generic type information",
                            f.getName(), clazz.getName()));
                    jo.put(f.getName(), dumpObject(ArrayList.class, hasDone));
                } else if (Map.class.isAssignableFrom(ct)) {
                    logger.warn(String.format(
                            "Field[%s] of class[%s] is type of Map, unable to dump it because it doesn't have java generic type information", f.getName(),
                            clazz.getName()));
                    jo.put(f.getName(), dumpObject(HashMap.class, hasDone));
                } else {
                    logger.debug(String.format("dumping %s, %s", f.getName(), ct.getName()));
                    JSONObject oj = dumpObject(ct, hasDone);
                    jo.put(f.getName(), oj);
                }
            }
        }
        clazz = clazz.getSuperclass();
    } while (clazz != null && clazz != Object.class);

    hasDone.pop();
    return jo;
}
 
Example 20
Source File: RuntimeInlineAnnotationReader.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public boolean hasFieldAnnotation(Class<? extends Annotation> annotationType, Field field) {
    return field.isAnnotationPresent(annotationType);
}