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

The following are Jave code examples for showing how to use isAnnotationPresent() of the java.lang.reflect.Field class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: nixmash-blog   File: JsoupHtmlParser.java   View Source Code Vote up 7 votes
private String parseSelector(Field f) {
    String selector = f.getAnnotation(Selector.class).value();

    Elements elems = doc.select(selector);

    if (elems.size() > 0) {
        final Element elem = elems.get(0);

        // Check which value annotation is present and retrieve data depending on the type of annotation
        if (f.isAnnotationPresent(TextValue.class)) {
            return elem.text();
        } else if (f.isAnnotationPresent(HtmlValue.class)) {
            return elem.html();
        } else if (f.isAnnotationPresent(AttributeValue.class)) {
            return elem.attr(f.getAnnotation(AttributeValue.class).name());
        } else
            return elem.text();
    }

    return null;
}
 
Example 2
Project: L2J-Global   File: NpcStringId.java   View Source Code Vote up 6 votes
private static void buildFastLookupTable()
{
	final Field[] fields = NpcStringId.class.getDeclaredFields();
	
	for (Field field : fields)
	{
		final int mod = field.getModifiers();
		if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && field.getType().equals(NpcStringId.class) && field.isAnnotationPresent(ClientString.class))
		{
			try
			{
				final ClientString annotation = field.getAnnotationsByType(ClientString.class)[0];
				final NpcStringId nsId = new NpcStringId(annotation.id());
				nsId.setName(annotation.message());
				nsId.setParamCount(parseMessageParameters(field.getName()));
				field.set(null, nsId);
				VALUES.put(nsId.getId(), nsId);
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "NpcStringId: Failed field access for '" + field.getName() + "'", e);
			}
		}
	}
}
 
Example 3
Project: PoiExcelExport2.0   File: ExcelExportService.java   View Source Code Vote up 6 votes
private List<CellDefinition> _getEntityFields(Class<?> loadCls){
	List<CellDefinition> definition=new LinkedList<CellDefinition>();
	Field[] fields=loadCls.getDeclaredFields();
	for(Field f:fields){
		if(!f.isAnnotationPresent(EntityAttribute.class)){
			continue;
		}
		CellDefinition define=new CellDefinition();
		EntityAttribute attr=f.getAnnotation(EntityAttribute.class);
		define.setRow(attr.row());
		define.setCol(attr.col());
		define.setAnnotation(attr);
		define.setBroken(attr.broken());
		define.setCellStyle(attr.cellStyle());
		define.setField(f);
		define.setFontStyle(attr.fontStyle());
		define.setMerge(attr.merge());
		define.setRequired(attr.required());
		definition.add(define);
	}
	return definition;
}
 
Example 4
Project: azeroth   File: CacheHandler.java   View Source Code Vote up 6 votes
/**
 * 生成按主键查询缓存定义
 * @param mapperClass
 * @param entityClass
 * @return
 */
private QueryMethodCache generateQueryByPKMethod(Class<?> mapperClass, Class<?> entityClass) {
    QueryMethodCache methodCache = null;
    Field[] fields = entityClass.getDeclaredFields();
    //主键key前缀
    for (Field field : fields) {
        if (field.isAnnotationPresent(Id.class)) {
            methodCache = new QueryMethodCache();
            methodCache.isPk = true;
            methodCache.collectionResult = false;
            methodCache.keyPattern = entityClass.getSimpleName() + ".id:%s";
            methodCache.methodName = mapperClass.getName() + "." + methodDefine.selectName();
            methodCache.cacheGroupKey = entityClass.getSimpleName() + GROUPKEY_SUFFIX;
            //
            groupKeys.add(methodCache.cacheGroupKey);
        }
    }
    return methodCache;
}
 
Example 5
Project: PoiExcelExport   File: ExcelExportService.java   View Source Code Vote up 6 votes
private List<CellDefinition> _getEntityFields(Class<?> loadCls){
	List<CellDefinition> definition=new LinkedList<CellDefinition>();
	Field[] fields=loadCls.getDeclaredFields();
	for(Field f:fields){
		if(!f.isAnnotationPresent(EntityAttribute.class)){
			continue;
		}
		CellDefinition define=new CellDefinition();
		EntityAttribute attr=f.getAnnotation(EntityAttribute.class);
		define.setRow(attr.row());
		define.setCol(attr.col());
		define.setAnnotation(attr);
		define.setBroken(attr.broken());
		define.setCellStyle(attr.cellStyle());
		define.setField(f);
		define.setFontStyle(attr.fontStyle());
		define.setMerge(attr.merge());
		define.setRequired(attr.required());
		definition.add(define);
	}
	return definition;
}
 
Example 6
Project: crud-admin-spring-boot-starter   File: CrudAdminRepository.java   View Source Code Vote up 6 votes
public Field getId() {
	if (idField == null) {
		List<Field> fieldNames = new ArrayList<>();
		Class<?> c = getDomainType();
		while (c != null) {
			for (Field field : c.getDeclaredFields()) {
				if (field.isAnnotationPresent(Id.class)) {
					field.setAccessible(true);
					fieldNames.add(field);
				}
			}
			c = c.getSuperclass();
		}
		idField = fieldNames.get(0);
	}
	return idField;
}
 
Example 7
Project: BaseClient   File: Option.java   View Source Code Vote up 6 votes
public void setValue(boolean value) {
    this.value = value;
    Field[] arrfield = this.mod.getClass().getDeclaredFields();
    int n = arrfield.length;
    int n2 = 0;
    while (n2 < n) {
        Field field = arrfield[n2];
        field.setAccessible(true);
        if (field.isAnnotationPresent(Op.class) && field.getName().equalsIgnoreCase(this.name)) {
            try {
                field.setBoolean(this.mod, value);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        ++n2;
    }
    if (Gui.instance != null) {
        Gui.instance.reloadOptions();
    }
    OptionManager.save();
}
 
Example 8
Project: picocli   File: CommandLine.java   View Source Code Vote up 5 votes
/** Returns the default arity {@code Range}: for {@link Option options} this is 0 for booleans and 1 for
 * other types, for {@link Parameters parameters} booleans have arity 0, arrays or Collections have
 * arity "0..*", and other types have arity 1.
 * @param field the field whose default arity to return
 * @return a new {@code Range} indicating the default arity of the specified field
 * @since 2.0 */
public static Range defaultArity(Field field) {
    Class<?> type = field.getType();
    if (field.isAnnotationPresent(Option.class)) {
        Class<?>[] typeAttribute = ArgSpecBuilder.inferTypes(type, field.getAnnotation(Option.class).type(), field.getGenericType());
        boolean zeroArgs = isBoolean(type) || (isMultiValue(type) && isBoolean(typeAttribute[0]));
        return zeroArgs ? Range.valueOf("0") : Range.valueOf("1");
    }
    if (isMultiValue(type)) {
        return Range.valueOf("0..1");
    }
    return Range.valueOf("1");// for single-valued fields (incl. boolean positional parameters)
}
 
Example 9
Project: Nukkit-Java9   File: SimpleConfig.java   View Source Code Vote up 5 votes
private String getPath(Field field) {
    String path = null;
    if (field.isAnnotationPresent(Path.class)) {
        Path pathDefine = field.getAnnotation(Path.class);
        path = pathDefine.value();
    }
    if (path == null || path.isEmpty()) path = field.getName().replaceAll("_", ".");
    if (Modifier.isFinal(field.getModifiers())) return null;
    if (Modifier.isPrivate(field.getModifiers())) field.setAccessible(true);
    return path;
}
 
Example 10
Project: lyra2-java   File: CommandLine.java   View Source Code Vote up 5 votes
private void assertNoMissingParameters(Field field, int arity, Stack<String> args) {
    if (arity > args.size()) {
        int actualSize = 0;
        @SuppressWarnings("unchecked")
        Stack<String> copy = (Stack<String>) args.clone();
        while (!copy.isEmpty()) {
            actualSize += split(copy.pop(), field).length;
            if (actualSize >= arity) { return; }
        }
        if (arity == 1) {
            if (field.isAnnotationPresent(Option.class)) {
                throw new MissingParameterException("Missing required parameter for " +
                        optionDescription("", field, 0));
            }
            Range indexRange = Range.parameterIndex(field);
            Help.IParamLabelRenderer labelRenderer = Help.createMinimalParamLabelRenderer();
            String sep = "";
            String names = "";
            int count = 0;
            for (int i = indexRange.min; i < positionalParametersFields.size(); i++) {
                if (Range.parameterArity(positionalParametersFields.get(i)).min > 0) {
                    names += sep + labelRenderer.renderParameterLabel(positionalParametersFields.get(i),
                            Help.Ansi.OFF, Collections.<IStyle>emptyList());
                    sep = ", ";
                    count++;
                }
            }
            String msg = "Missing required parameter";
            Range paramArity = Range.parameterArity(field);
            if (paramArity.isVariable) {
                msg += "s at positions " + indexRange + ": ";
            } else {
                msg += (count > 1 ? "s: " : ": ");
            }
            throw new MissingParameterException(msg + names);
        }
        throw new MissingParameterException(optionDescription("", field, 0) +
                " requires at least " + arity + " values, but only " + args.size() + " were specified.");
    }
}
 
Example 11
Project: mybatis-dynamic-query   File: EntityHelper.java   View Source Code Vote up 5 votes
static Column getColumnByProperty(final String propertyName, final Field[] properties) {
    Field matchProperty = getPropertyField(propertyName, properties);
    if (matchProperty.isAnnotationPresent(Column.class)) {
        return matchProperty.getAnnotation(Column.class);
    }

    return null;
}
 
Example 12
Project: GitHub   File: ReflectionUtils.java   View Source Code Vote up 5 votes
public static Set<Field> getDeclaredColumnFields(Class<?> type) {
	Set<Field> declaredColumnFields = Collections.emptySet();
	
	if (ReflectionUtils.isSubclassOf(type, Model.class) || Model.class.equals(type)) {
		declaredColumnFields = new LinkedHashSet<Field>();
		
		Field[] fields = type.getDeclaredFields();
		Arrays.sort(fields, new Comparator<Field>() {
			@Override
			public int compare(Field field1, Field field2) {
				return field2.getName().compareTo(field1.getName());
			}
		});
		for (Field field : fields) {
			if (field.isAnnotationPresent(Column.class)) {
				declaredColumnFields.add(field);
			}
		}

		Class<?> parentType = type.getSuperclass();
		if (parentType != null) {
			declaredColumnFields.addAll(getDeclaredColumnFields(parentType));
		}
	}
	
	return declaredColumnFields;		
}
 
Example 13
Project: Neutrino   File: NeutrinoObjectMapper.java   View Source Code Vote up 5 votes
protected void collectFields(Map<String, FieldData> cachedFields, Class<? super T> clazz) throws ObjectMappingException {
    if (this.fieldDataMapCache == null) {
        this.fieldDataMapCache = cachedFields;
        this.fieldsToProcess = Lists.newArrayList();
    }

    for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(Setting.class)) {
            fieldsToProcess.add(field);
        }
    }
}
 
Example 14
Project: mybatis-dynamic-query   File: EntityCache.java   View Source Code Vote up 5 votes
private Map<String, ColumnInfo> getPropertyColumnInfoMap(Class entityClass) {
    if (entityClass == null) {
        throw new NullPointerException(ENTITY_CLASS);
    }

    Map<String, ColumnInfo> propertyDbColumnMap;
    if (columnInfoCacheMap.containsKey(entityClass)) {
        propertyDbColumnMap = columnInfoCacheMap.get(entityClass);
    } else {
        Map<String, ColumnInfo> map = new ConcurrentHashMap<>();
        Field[] properties = ReflectHelper.getProperties(entityClass);

        for (Field field : properties) {
            field.setAccessible(true);
            // filter Transient
            if (field.isAnnotationPresent(Transient.class)) {
                continue;
            }

            ColumnInfo columnInfo = new ColumnInfo();
            columnInfo.setField(field);
            String pName = field.getName();
            String columnName = EntityHelper.getColumnNameByProperty(pName, properties);
            columnInfo.setColumnName(columnName);

            Column column = EntityHelper.getColumnByProperty(pName, properties);
            String tableOrAlias = column == null ? "" : column.table();
            columnInfo.setTableOrAlias(tableOrAlias);
            map.put(pName, columnInfo);
        }
        columnInfoCacheMap.put(entityClass, map);
        propertyDbColumnMap = map;
    }

    return propertyDbColumnMap;
}
 
Example 15
Project: minlia-iot   File: XmlApiDeserializer.java   View Source Code Vote up 5 votes
protected <E> E makeResponseXmlBody(Element rootElement,
    Class<E> clazz)
    throws IllegalAccessException, InstantiationException {
  E entity = clazz.newInstance();
  for (Field field : clazz.getDeclaredFields()) {
    field.setAccessible(true);
    if (field.isAnnotationPresent(XmlElement.class)) {
      dealXmlElementAnnotation(rootElement, field, entity);
    } else if (field.isAnnotationPresent(XmlElementArray.class)) {
      dealXmlElementArrayAnnotation(rootElement, field, entity);
    }
  }
  return entity;
}
 
Example 16
Project: BaseClient   File: ValueManager.java   View Source Code Vote up 5 votes
public static void init() throws IllegalArgumentException, IllegalAccessException {
    for (Module mod : ModuleManager.moduleList) {
        Field[] arrfield = mod.getClass().getDeclaredFields();
        int n = arrfield.length;
        int n2 = 0;
        while (n2 < n) {
            Field field = arrfield[n2];
            field.setAccessible(true);
            if (field.isAnnotationPresent(Val.class)) {
                Value value = new Value(mod, StringUtil.capitalize(field.getName()), field.getDouble(mod), new double[]{((Val)field.getAnnotation(Val.class)).min(), ((Val)field.getAnnotation(Val.class)).max()}, ((Val)field.getAnnotation(Val.class)).increment());
                valueList.add(value);
            }
            ++n2;
        }
    }
    valueList.sort(new Comparator<Value>(){

        @Override
        public int compare(Value v1, Value v2) {
            String s1 = v1.name;
            String s2 = v2.name;
            return s1.compareTo(s2);
        }
    });
    ValueManager.load();
    ValueManager.save();
}
 
Example 17
Project: tauren   File: ResultSetHandlerFactory.java   View Source Code Vote up 5 votes
/**
 * 获取字段名
 * <p>如果字段被{@link Column}修饰,则使用用户自定义名称</p>
 * <p>否则返回字段名的下划线表示,例如:userName ==> user_name</p>
 */
private static String getFieldName(Field field) {
    if (field.isAnnotationPresent(Column.class)) {
        Column anno = field.getAnnotation(Column.class);
        if (StringUtils.isNotBlank(anno.value())) {
            return anno.value();
        }
    }

    return ClassUtil.underline(field.getName());
}
 
Example 18
Project: picocli   File: CommandLine.java   View Source Code Vote up 4 votes
/** Returns a new {@code Range} based on the {@link Parameters#arity()} annotation on the specified field,
 * or the field type's default arity if no arity was specified.
 * @param field the field whose Parameters annotation to inspect
 * @return a new {@code Range} based on the Parameters arity annotation on the specified field */
public static Range parameterArity(Field field) {
    return field.isAnnotationPresent(Parameters.class)
            ? adjustForType(Range.valueOf(field.getAnnotation(Parameters.class).arity()), field)
            : new Range(0, 0, false, true, "0");
}
 
Example 19
Project: bitflyer4j   File: EntityTest.java   View Source Code Vote up 4 votes
private void testBuilder(Class<?> clazz) throws ReflectiveOperationException {

        Object builder = clazz.getMethod("builder").invoke(clazz);
        assertNotNull(builder.toString());
        assertEquals(builder.hashCode(), builder.hashCode());
        assertTrue(builder.equals(builder));

        Method build = builder.getClass().getMethod("build");

        Object emptyEntity = testGet(build.invoke(builder));
        assertNotNull(emptyEntity.toString());
        assertEquals(emptyEntity.hashCode(), emptyEntity.hashCode());
        assertTrue(emptyEntity.equals(emptyEntity));
        assertFalse(emptyEntity.equals(clazz));
        assertFalse(emptyEntity.equals(null));

        for (Field field : clazz.getDeclaredFields()) {

            if (!field.isAnnotationPresent(SerializedName.class)) {
                continue;
            }

            for (Method method : builder.getClass().getMethods()) {

                if (method.getReturnType() != builder.getClass()) {
                    continue;
                }

                method.invoke(builder, ARGS.get(method.getParameterTypes()[0]));

            }

        }

        Object filledEntity = testGet(build.invoke(builder));
        assertNotNull(filledEntity.toString());
        assertEquals(filledEntity.hashCode(), filledEntity.hashCode());
        assertTrue(filledEntity.equals(filledEntity));
        assertFalse(filledEntity.equals(clazz));
        assertFalse(filledEntity.equals(null));

    }
 
Example 20
Project: plpgsql-java-model   File: TemplaterEngine.java   View Source Code Vote up 2 votes
public Object replace(Object source, Object o, Field field) {

        logger.trace("source = "+source.getClass().getName() + "; o = "+o.getClass().getName() + "; field = "+field);

        // check class annotations


        if (o.getClass().isAnnotationPresent(Template.class) && except(source,o)) {

            return template(o);

        }


        if (o.getClass().isAnnotationPresent(Stringable.class)) {


            return o.toString();


        }

        // check field annotations
        if (field.isAnnotationPresent(Hidden.class)) {
            return null;
        }

        if (field.isAnnotationPresent(Stringable.class)) {
            return o.toString();
        }

        if (field.isAnnotationPresent(Replace.class)) {
            return field.getAnnotation(Replace.class).value();
        }

        // check type of object
        if (o instanceof Collection) {
            return ((Collection<Object>) o).stream().map(e -> replace(source, e, field)).collect(Collectors.toList());
        }

        if (simpleTypes.contains(o.getClass()) || o.getClass().isPrimitive() || o.getClass().isEnum()) {
            return o;
        }

        return convert(o);
    }