java.lang.reflect.Field#getDeclaredAnnotation ( )源码实例Demo

下面列出了java.lang.reflect.Field#getDeclaredAnnotation ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: core-ng-project   文件: BeanValidatorBuilder.java
private void buildStringValidation(CodeBuilder builder, Field field, String pathLiteral) {
    NotBlank notBlank = field.getDeclaredAnnotation(NotBlank.class);
    if (notBlank != null) builder.indent(2).append("if (bean.{}.isBlank()) errors.add({}, {}, null);\n", field.getName(), pathLiteral, variable(notBlank.message()));

    buildSizeValidation(builder, field, pathLiteral, "length");

    Pattern pattern = field.getDeclaredAnnotation(Pattern.class);
    if (pattern != null) {
        String patternFieldName = field.getName() + "Pattern" + (index++);
        String patternVariable = variable(pattern.value());
        this.builder.addField("private final java.util.regex.Pattern {} = java.util.regex.Pattern.compile({});", patternFieldName, patternVariable);
        builder.indent(2).append("if (!this.{}.matcher(bean.{}).matches()) errors.add({}, {}, java.util.Map.of(\"value\", bean.{}, \"pattern\", {}));\n",
                patternFieldName, field.getName(), pathLiteral, variable(pattern.message()),
                field.getName(), patternVariable);
    }
}
 
源代码2 项目: api-boot   文件: DecimalAccuracyFilter.java
@Override
public Object process(Object object, String name, Object value) {
    try {
        // find field
        Field field = ReflectionUtils.findField(object.getClass(), name);
        // Have ApiBootDecimalAccuracy Annotation
        // Value is BigDecimal Instance
        if (field.isAnnotationPresent(ApiBootDecimalAccuracy.class) && value instanceof BigDecimal) {
            ApiBootDecimalAccuracy decimalAccuracy = field.getDeclaredAnnotation(ApiBootDecimalAccuracy.class);
            BigDecimal decimalValue = (BigDecimal) value;
            return decimalValue.setScale(decimalAccuracy.scale(), decimalAccuracy.roundingMode());
        }
    } catch (Exception e) {
        //ignore
        return value;
    }
    return value;
}
 
源代码3 项目: SPADE   文件: LoadableFieldHelper.java
public static String allLoadableFieldsToString(Object object) throws Exception{
	StringBuffer string = new StringBuffer();
	Class<?> enclosingClass = object.getClass();
	Set<Field> loadableFields = getAllLoadableFields(enclosingClass);
	if(loadableFields != null){
		for(Field loadableField : loadableFields){
			LoadableField loadableFieldAnnotation = loadableField.getDeclaredAnnotation(LoadableField.class);
			String name = loadableFieldAnnotation.name();
			Object value = getFieldValue(object, loadableField);
			if(value == null){
				string.append(name).append("=").append("(null)").append(" ");
			}else{
				if(loadableField.getType().isArray()){
					string.append(name).append("=").append(Arrays.toString((Object[])value)).append(" ");
				}else{
					string.append(name).append("=").append(value).append(" ");
				}
			}
		}
	}
	if(string.length() > 0){
		string = string.deleteCharAt(string.length() - 1);
	}
	return string.toString();
}
 
源代码4 项目: gd-generator   文件: MysqlHandler.java
private MysqlColumnMeta parseColumn(Field field) {
    String type = getMysqlType(field);
    Column column = field.getDeclaredAnnotation(Column.class);
    String name, label = null;
    if (column != null) {
        name = StringUtils.isBlank(column.name()) ? field.getName() : column.name();
    } else {
        name = field.getName();
    }

    final io.gd.generator.annotation.Field fieldAnno = field.getDeclaredAnnotation(io.gd.generator.annotation.Field.class);

    if (fieldAnno != null) {
        label = fieldAnno.label();
    }

    MysqlColumnMeta mysqlColumnMeta = new MysqlColumnMeta();
    mysqlColumnMeta.setName(StringUtils.camelToUnderline(name));
    mysqlColumnMeta.setType(type);
    mysqlColumnMeta.setComment(label);
    return mysqlColumnMeta;
}
 
源代码5 项目: rheem   文件: Operator.java
/**
 * Collects all fields of this instance that have a {@link EstimationContextProperty} annotation.
 *
 * @return the fields
 */
default Collection<String> getEstimationContextProperties() {
    Set<String> properties = new HashSet<>(2);
    Queue<Class<?>> classQueue = new LinkedList<>();
    classQueue.add(this.getClass());
    while (!classQueue.isEmpty()) {
        final Class<?> cls = classQueue.poll();
        if (cls.getSuperclass() != null) classQueue.add(cls.getSuperclass());
        for (Field declaredField : cls.getDeclaredFields()) {
            final EstimationContextProperty annotation = declaredField.getDeclaredAnnotation(EstimationContextProperty.class);
            if (annotation != null) {
                properties.add(declaredField.getName());
            }
        }
    }
    return properties;
}
 
源代码6 项目: core-ng-project   文件: MongoClassValidator.java
@Override
public void visitField(Field field, String parentPath) {
    if (field.isAnnotationPresent(Id.class)) {
        validateId(field, parentPath == null);
    } else {
        core.framework.mongo.Field mongoField = field.getDeclaredAnnotation(core.framework.mongo.Field.class);
        if (mongoField == null)
            throw new Error(format("mongo entity field must have @Field, field={}", Fields.path(field)));
        String mongoFieldName = mongoField.name();

        Set<String> fields = this.fields.computeIfAbsent(parentPath, key -> Sets.newHashSet());
        if (fields.contains(mongoFieldName)) {
            throw new Error(format("found duplicate field, field={}, mongoField={}", Fields.path(field), mongoFieldName));
        }
        fields.add(mongoFieldName);
    }
}
 
源代码7 项目: core-ng-project   文件: DatabaseClassValidator.java
@Override
public void visitEnum(Class<?> enumClass) {
    Set<String> enumValues = Sets.newHashSet();
    List<Field> fields = Classes.enumConstantFields(enumClass);
    for (Field field : fields) {
        DBEnumValue enumValue = field.getDeclaredAnnotation(DBEnumValue.class);
        if (enumValue == null)
            throw new Error("db enum must have @DBEnumValue, field=" + Fields.path(field));

        boolean added = enumValues.add(enumValue.value());
        if (!added)
            throw new Error(format("found duplicate db enum value, field={}, value={}", Fields.path(field), enumValue.value()));

        Property property = field.getDeclaredAnnotation(Property.class);
        if (property != null)
            throw new Error("db enum must not have json annotation, please separate view and entity, field=" + Fields.path(field));
    }
}
 
源代码8 项目: core-ng-project   文件: DeleteQueryBuilder.java
static String build(Class<?> entityClass) {
    Table table = entityClass.getDeclaredAnnotation(Table.class);
    var builder = new StringBuilder("DELETE FROM ").append(table.name()).append(" WHERE ");
    int index = 0;
    for (Field field : Classes.instanceFields(entityClass)) {
        if (field.isAnnotationPresent(PrimaryKey.class)) {
            Column column = field.getDeclaredAnnotation(Column.class);
            if (index > 0) builder.append(" AND ");
            builder.append(column.name()).append(" = ?");
            index++;
        }
    }
    return builder.toString();
}
 
源代码9 项目: gd-generator   文件: MybatisMapperHandler.java
@Override
protected void write(MybatisMapperMeta merged, Class<?> entityClass) throws Exception {

    Map<String, Object> model = new HashMap<>();
    Field[] fields = entityClass.getDeclaredFields();
    for (Field field : fields) {
        Id declaredAnnotation = field.getDeclaredAnnotation(Id.class);
        if (declaredAnnotation != null) {
            merged.setIdType(field.getType().getSimpleName());
            merged.setIdPropName(field.getName());
            break;
        }
    }
    if (StringUtils.isBlank(merged.getIdPropName())) {
        merged.setIdPropName("id");//id as default
    }

    model.put("meta", merged);
    String mapper = renderTemplate("mybatisMapper", model);
    File file = new File(getMapperFilePath(entityClass));

    if (file.exists()) {
        file.delete();
    }
    file.createNewFile();
    try (FileOutputStream os = new FileOutputStream(file)) {
        os.write(mapper.getBytes());
    }
}
 
源代码10 项目: ignite   文件: CacheConfigurationSplitterImpl.java
/**
 * Builds {@link CacheConfigurationEnrichment} from given config.
 * It extracts all field values to enrichment object replacing values of that fields with default.
 *
 * @param cfgCls Configuration class.
 * @param cfg Configuration to build enrichment from.
 * @param dfltCfg Default configuration to replace enriched values with default.
 * @param <T> Configuration class.
 * @return Enrichment object for given config.
 * @throws IllegalAccessException If failed.
 */
private <T> CacheConfigurationEnrichment buildEnrichment(
    Class<T> cfgCls,
    T cfg,
    T dfltCfg
) throws IllegalAccessException {
    Map<String, byte[]> enrichment = new HashMap<>();
    Map<String, String> fieldClsNames = new HashMap<>();

    for (Field field : cfgCls.getDeclaredFields()) {
        if (field.getDeclaredAnnotation(SerializeSeparately.class) != null) {
            field.setAccessible(true);

            Object val = field.get(cfg);

            byte[] serializedVal = serialize(field.getName(), val);

            enrichment.put(field.getName(), serializedVal);

            fieldClsNames.put(field.getName(), val != null ? val.getClass().getName() : null);

            // Replace field in original configuration with default value.
            field.set(cfg, field.get(dfltCfg));
        }
    }

    return new CacheConfigurationEnrichment(enrichment, fieldClsNames);
}
 
源代码11 项目: gd-generator   文件: VoHandler.java
private String handleFieldLabel(Field field, String label, String format) {
	if (isBlank(label)) {
		if (field.isAnnotationPresent(io.gd.generator.annotation.Field.class)) {
			final io.gd.generator.annotation.Field fieldAnno = field.getDeclaredAnnotation(io.gd.generator.annotation.Field.class);
			return fieldAnno.label();
		} else {
			logger.warn(format + ",默认使用 " + field.getName());
			return field.getName();
		}
	} else {
		return label;
	}
}
 
源代码12 项目: core-ng-project   文件: JSONClassValidator.java
@Override
public void visitField(Field field, String parentPath) {
    Property property = field.getDeclaredAnnotation(Property.class);
    if (property == null)
        throw new Error("field must have @Property, field=" + Fields.path(field));

    String name = property.name();
    if (name.isBlank()) throw new Error("@Property name attribute must not be blank, field=" + Fields.path(field));

    boolean added = visitedProperties.computeIfAbsent(parentPath, key -> Sets.newHashSet()).add(name);
    if (!added) {
        throw new Error(format("found duplicate property, field={}, name={}", Fields.path(field), name));
    }
}
 
源代码13 项目: halyard   文件: Node.java
private boolean isSecretFile(Field field) {
  if (field.getDeclaredAnnotation(SecretFile.class) != null) {
    try {
      field.setAccessible(true);
      String val = (String) field.get(this);
      return EncryptedSecret.isEncryptedSecret(val);
    } catch (IllegalAccessException e) {
      return false;
    }
  }
  return false;
}
 
源代码14 项目: core-ng-project   文件: SelectQuery.java
private String columns(List<Field> fields) {
    var builder = new StringBuilder();
    int index = 0;
    for (Field field : fields) {
        Column column = field.getDeclaredAnnotation(Column.class);
        if (index > 0) builder.append(", ");
        builder.append(column.name());
        index++;
    }
    return builder.toString();
}
 
源代码15 项目: core-ng-project   文件: SelectQuery.java
private String getSQL(List<Field> fields) {
    var builder = new StringBuilder("SELECT ").append(columns).append(" FROM ").append(table).append(" WHERE ");
    for (Field field : fields) {
        if (field.isAnnotationPresent(PrimaryKey.class)) {
            Column column = field.getDeclaredAnnotation(Column.class);
            if (primaryKeyColumns > 0) builder.append(" AND ");
            builder.append(column.name()).append(" = ?");
            primaryKeyColumns++;
        }
    }
    return builder.toString();
}
 
源代码16 项目: core-ng-project   文件: DatabaseClassValidator.java
@Override
public void visitField(Field field, String parentPath) {
    Column column = field.getDeclaredAnnotation(Column.class);
    if (column == null) throw new Error("db entity field must have @Column, field=" + Fields.path(field));

    Property property = field.getDeclaredAnnotation(Property.class);
    if (property != null)
        throw new Error("db entity field must not have json annotation, please separate view and entity, field=" + Fields.path(field));


    boolean added = columns.add(column.name());
    if (!added) {
        throw new Error(format("found duplicate column, field={}, column={}", Fields.path(field), column.name()));
    }

    PrimaryKey primaryKey = field.getDeclaredAnnotation(PrimaryKey.class);
    if (primaryKey != null) {
        if (validateView) throw new Error("db view field must not have @PrimaryKey, field=" + Fields.path(field));
        foundPrimaryKey = true;
        validatePrimaryKey(primaryKey, field.getType(), field);
    }

    try {
        // entity constructed by "new" with default value will break partialUpdate accidentally, due to fields are not null will be updated to db
        if (!validateView && field.get(entityWithDefaultValue) != null)
            throw new Error("db entity field must not have default value, field=" + Fields.path(field));
    } catch (ReflectiveOperationException e) {
        throw new Error(e);
    }
}
 
源代码17 项目: COLA   文件: TestExecutor.java
private void injectWiredBean(Class<?> testClz, Object testInstance) {
   Field[] fields = testClz.getDeclaredFields();
   if(fields == null) {
       return;
   }
   for(Field field : fields) {
       String beanName = field.getName();
       Annotation autowiredAnn = field.getDeclaredAnnotation(Autowired.class);
       if (autowiredAnn == null) {
           continue;
       }
       trySetFieldValue(field, testInstance, beanName);
   }
}
 
源代码18 项目: elasticsearch-mapper   文件: DateFieldMapper.java
public static void mapDataType(XContentBuilder mappingBuilder, Field field) throws IOException {
    if (!isValidDateType(field)) {
        throw new IllegalArgumentException(
                String.format("field type[%s] is invalid type of date.", field.getType()));
    }

    if (field.isAnnotationPresent(DateField.class)) {
        DateField dateField = field.getDeclaredAnnotation(DateField.class);
        mapDataType(mappingBuilder, dateField);
        return;
    }

    mappingBuilder.field("type", "date");
}
 
源代码19 项目: gd-generator   文件: MybatisXmlHandler.java
private String parseEnum(Field field) {
    Enumerated enumerated = field.getDeclaredAnnotation(Enumerated.class);
    if (enumerated != null) {
        EnumType value = enumerated.value();
        if (EnumType.STRING.equals(value))
            return "org.apache.ibatis.type.EnumTypeHandler";
    }
    if (config.isUseEnumOrdinalTypeHandlerByDefault()) {
        return "org.apache.ibatis.type.EnumOrdinalTypeHandler";
    } else {
        return null;
    }
}
 
源代码20 项目: night-config   文件: AnnotationUtils.java
/**
 * Checks that the value of a field corresponds to its spec annotation, if any.
 * <p>
 * The check should apply to the field's value, not the config value. That is, when
 * converting a field to a config value, the check should apply before the conversion
 * [fieldValue -> configValue] and, when converting a config value to a field, the check
 * should apply after the conversion [configValue -> fieldValue].
 *
 * @param field the field to check
 * @param value the field's value
 */
static void checkField(Field field, Object value) {
	//--- Misc checks ---
	SpecNotNull specNotNull = field.getDeclaredAnnotation(SpecNotNull.class);
	if (specNotNull != null) {
		checkNotNull(field, value);
		return;
	}
	SpecClassInArray specClassInArray = field.getDeclaredAnnotation(SpecClassInArray.class);
	if (specClassInArray != null) {
		checkFieldSpec(field, value, specClassInArray);
		return;
	}

	//--- String checks ---
	SpecStringInArray specStringInArray = field.getDeclaredAnnotation(SpecStringInArray.class);
	if (specStringInArray != null) {
		checkFieldSpec(field, value, specStringInArray);
		return;
	}
	SpecStringInRange specStringInRange = field.getDeclaredAnnotation(SpecStringInRange.class);
	if (specStringInRange != null) {
		checkFieldSpec(field, value, specStringInRange);
		return;
	}

	//--- Primitive checks ---
	SpecDoubleInRange specDoubleInRange = field.getDeclaredAnnotation(SpecDoubleInRange.class);
	if (specDoubleInRange != null) {
		checkFieldSpec(field, value, specDoubleInRange);
		return;
	}
	SpecFloatInRange specFloatInRange = field.getDeclaredAnnotation(SpecFloatInRange.class);
	if (specFloatInRange != null) {
		checkFieldSpec(field, value, specFloatInRange);
		return;
	}
	SpecLongInRange specLongInRange = field.getDeclaredAnnotation(SpecLongInRange.class);
	if (specLongInRange != null) {
		checkFieldSpec(field, value, specLongInRange);
		return;
	}
	SpecIntInRange specIntInRange = field.getDeclaredAnnotation(SpecIntInRange.class);
	if (specIntInRange != null) {
		checkFieldSpec(field, value, specIntInRange);
	}

	// --- Enum check ---
	SpecEnum specEnum = field.getDeclaredAnnotation(SpecEnum.class);
	if (specEnum != null) {
		checkFieldSpec(field, value, specEnum);
	}

	// --- Custom check with a validator --
	SpecValidator specValidator = field.getDeclaredAnnotation(SpecValidator.class);
	if (specValidator != null) {
		checkFieldSpec(field, value, specValidator);
	}
}