List of usage examples for java.lang.reflect Modifier isFinal
public static boolean isFinal(int mod)
From source file:com.swingtech.commons.testing.JavaBeanTester.java
private static Object buildMockValue(Class<?> clazz) { if (!Modifier.isFinal(clazz.getModifiers())) { // Insert a call to your favourite mocking framework here return null; } else {//from www .ja v a2 s .c o m return null; } }
From source file:org.eclipse.skalli.core.persistence.EntityHelper.java
private static void doNormalize(EntityBase entity) { if (entity == null) { return;//from w w w . ja va 2 s . c o m } Class<?> currentClass = entity.getClass(); while (currentClass != null) { for (Field field : currentClass.getDeclaredFields()) { try { // do not try to change constants or transient fields int modifiers = field.getModifiers(); if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) { continue; } field.setAccessible(true); // ensure, thet the value is non null Object value = field.get(entity); if (value == null) { instantiateField(entity, field); } else { // for non-null collections or maps, ensure that there // are no null entries or empty strings Class<?> type = field.getType(); if (Collection.class.isAssignableFrom(type)) { Collection<?> collection = (Collection<?>) value; ArrayList<Object> remove = new ArrayList<Object>(); for (Object entry : collection) { if (entry instanceof String && StringUtils.isBlank((String) entry)) { remove.add(entry); } } collection.removeAll(remove); field.set(entity, collection); } else if (Map.class.isAssignableFrom(type)) { Map<?, ?> map = (Map<?, ?>) value; ArrayList<Object> remove = new ArrayList<Object>(); for (Entry<?, ?> entry : map.entrySet()) { if (entry.getValue() instanceof String && StringUtils.isBlank((String) entry.getValue())) { remove.add(entry.getKey()); } } for (Object key : remove) { map.remove(key); } field.set(entity, map); } } } catch (UnsupportedOperationException e) { // TODO exception handling/logging // some collections/map may not support remove throw new RuntimeException(e); } catch (IllegalArgumentException e) { //TODO exception handling/logging throw new RuntimeException(e); } catch (IllegalAccessException e) { //TODO exception handling/logging throw new RuntimeException(e); } } currentClass = currentClass.getSuperclass(); } }
From source file:de.codesourcery.eve.skills.util.SpringBeanInjector.java
private void doInjectDependencies(Object obj) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { Class<?> currentClasz = obj.getClass(); do {/* ww w. ja v a 2 s .c o m*/ // inject fields for (Field f : currentClasz.getDeclaredFields()) { final int m = f.getModifiers(); if (Modifier.isStatic(m) || Modifier.isFinal(m)) { continue; } final Resource annot = f.getAnnotation(Resource.class); if (annot != null) { if (!f.isAccessible()) { f.setAccessible(true); } if (log.isTraceEnabled()) { log.trace("doInjectDependencies(): Setting field " + f.getName() + " with bean '" + annot.name() + "'"); } f.set(obj, getBean(annot.name())); } } // inject methods for (Method method : currentClasz.getDeclaredMethods()) { final int m = method.getModifiers(); if (Modifier.isStatic(m) || Modifier.isAbstract(m)) { continue; } if (method.getParameterTypes().length != 1) { continue; } if (!method.getName().startsWith("set")) { continue; } final Resource annot = method.getAnnotation(Resource.class); if (annot != null) { if (!method.isAccessible()) { method.setAccessible(true); } if (log.isTraceEnabled()) { log.trace("doInjectDependencies(): Invoking setter method " + method.getName() + " with bean '" + annot.name() + "'"); } method.invoke(obj, getBean(annot.name())); } } currentClasz = currentClasz.getSuperclass(); } while (currentClasz != null); }
From source file:py.una.pol.karaku.log.LogPostProcessor.java
/** * Revisa todos los mtodos o campos que tengan la anotacin {@link Log} y * le asigna el valor el Log del bean en cuestin. * /* ww w . j ava 2 s. co m*/ * <br /> * * {@inheritDoc} * * @param bean * bean a procesar * @param beanName * nombre del bean * @return el mismo bean * @throws BeansException * nunca */ @Override public Object postProcessBeforeInitialization(final Object bean, final String beanName) { ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { @Override public void doWith(Field field) throws IllegalAccessException { if (!Modifier.isFinal(field.getModifiers())) { field.setAccessible(true); Log log = field.getAnnotation(Log.class); field.set(bean, getLogger(bean, log)); } } }, new FieldFilter() { @Override public boolean matches(Field field) { return field.getAnnotation(Log.class) != null; } }); ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() { @Override public void doWith(Method method) throws IllegalAccessException { Log log = method.getAnnotation(Log.class); try { method.invoke(bean, getLogger(bean, log)); } catch (InvocationTargetException e) { LOGGER.warn("Error extracting proxy object from {}", bean.getClass().getName(), e); } } }, new MethodFilter() { @Override public boolean matches(Method method) { return method.getAnnotation(Log.class) != null; } }); return bean; }
From source file:com.palantir.ptoss.util.Reflections.java
/** * Returns whether or not the given {@link Field} is final. *///from w w w.jav a2 s . c o m public static boolean isFieldFinal(Field field) { int modifiers = field.getModifiers(); return Modifier.isFinal(modifiers); }
From source file:org.androidtransfuse.adapter.classes.ASTClassType.java
@Override public boolean isFinal() { return Modifier.isFinal(clazz.getModifiers()); }
From source file:org.datalorax.populace.core.walk.field.StdRawField.java
/** * {@inheritDoc} */ @Override public boolean isFinal() { return Modifier.isFinal(field.getModifiers()); }
From source file:cn.lambdalib.s11n.SerializationHelper.java
private List<Field> buildExposedFields(Class<?> type) { return FieldUtils.getAllFieldsList(type).stream().filter(f -> { Class<?> declaringClass = f.getDeclaringClass(); SerializeStrategy anno = declaringClass.getAnnotation(SerializeStrategy.class); ExposeStrategy strategy = anno == null ? ExposeStrategy.PUBLIC : anno.strategy(); boolean serializeAll = anno == null ? false : anno.all(); if (f.isAnnotationPresent(SerializeIncluded.class)) { return true; } else if (f.isAnnotationPresent(SerializeExcluded.class)) { return false; } else {//from w w w.j av a 2s . c om if (!serializeAll && !isS11nType(f.getType())) { return false; } else { int mod = f.getModifiers(); switch (strategy) { case PUBLIC: return Modifier.isPublic(mod) && !Modifier.isStatic(mod) && !Modifier.isFinal(mod); case ALL: return !Modifier.isStatic(mod) && !Modifier.isFinal(mod); default: return false; } } } }).map(f -> { f.setAccessible(true); return f; }).collect(Collectors.toList()); }
From source file:edu.usu.sdl.openstorefront.doc.EntityProcessor.java
private static void addFields(Class entity, EntityDocModel docModel) { if (entity != null) { Field[] fields = entity.getDeclaredFields(); for (Field field : fields) { //Skip static field if ((Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) == false) { EntityFieldModel fieldModel = new EntityFieldModel(); fieldModel.setName(field.getName()); fieldModel.setType(field.getType().getSimpleName()); fieldModel.setOriginClass(entity.getSimpleName()); fieldModel.setEmbeddedType(ReflectionUtil.isComplexClass(field.getType())); if (ReflectionUtil.isCollectionClass(field.getType())) { DataType dataType = (DataType) field.getAnnotation(DataType.class); if (dataType != null) { String typeClass = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeClass = dataType.actualClassName(); }//from ww w . ja v a 2 s.c o m fieldModel.setGenericType(typeClass); } } APIDescription description = (APIDescription) field.getAnnotation(APIDescription.class); if (description != null) { fieldModel.setDescription(description.value()); } for (Annotation annotation : field.getAnnotations()) { if (annotation.annotationType().getName().equals(APIDescription.class.getName()) == false) { EntityConstraintModel entityConstraintModel = new EntityConstraintModel(); entityConstraintModel.setName(annotation.annotationType().getSimpleName()); APIDescription annotationDescription = (APIDescription) annotation.annotationType() .getAnnotation(APIDescription.class); if (annotationDescription != null) { entityConstraintModel.setDescription(annotationDescription.value()); } //rules Object annObj = field.getAnnotation(annotation.annotationType()); if (annObj instanceof NotNull) { entityConstraintModel.setRules("Field is required"); } else if (annObj instanceof PK) { PK pk = (PK) annObj; entityConstraintModel.setRules("<b>Generated:</b> " + pk.generated()); fieldModel.setPrimaryKey(true); } else if (annObj instanceof FK) { FK fk = (FK) annObj; StringBuilder sb = new StringBuilder(); sb.append("<b>Foreign Key:</b> ").append(fk.value().getSimpleName()); sb.append(" (<b>Enforce</b>: ").append(fk.enforce()); sb.append(" <b>Soft reference</b>: ").append(fk.softReference()); if (StringUtils.isNotBlank(fk.referencedField())) { sb.append(" <b>Reference Field</b>: ").append(fk.referencedField()); } sb.append(" )"); entityConstraintModel.setRules(sb.toString()); } else if (annObj instanceof ConsumeField) { entityConstraintModel.setRules(""); } else if (annObj instanceof Size) { Size size = (Size) annObj; entityConstraintModel .setRules("<b>Min:</b> " + size.min() + " <b>Max:</b> " + size.max()); } else if (annObj instanceof Pattern) { Pattern pattern = (Pattern) annObj; entityConstraintModel.setRules("<b>Pattern:</b> " + pattern.regexp()); } else if (annObj instanceof Sanitize) { Sanitize sanitize = (Sanitize) annObj; entityConstraintModel .setRules("<b>Sanitize:</b> " + sanitize.value().getSimpleName()); } else if (annObj instanceof Unique) { Unique unique = (Unique) annObj; entityConstraintModel.setRules("<b>Handler:</b> " + unique.value().getSimpleName()); } else if (annObj instanceof ValidValueType) { ValidValueType validValueType = (ValidValueType) annObj; StringBuilder sb = new StringBuilder(); if (validValueType.value().length > 0) { sb.append(" <b>Values:</b> ").append(Arrays.toString(validValueType.value())); } if (validValueType.lookupClass().length > 0) { sb.append(" <b>Lookups:</b> "); for (Class lookupClass : validValueType.lookupClass()) { sb.append(lookupClass.getSimpleName()).append(" "); } } if (validValueType.enumClass().length > 0) { sb.append(" <b>Enumerations:</b> "); for (Class enumClass : validValueType.enumClass()) { sb.append(enumClass.getSimpleName()).append(" ("); sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")"); } } entityConstraintModel.setRules(sb.toString()); } else if (annObj instanceof Min) { Min min = (Min) annObj; entityConstraintModel.setRules("<b>Min value:</b> " + min.value()); } else if (annObj instanceof Max) { Max max = (Max) annObj; entityConstraintModel.setRules("<b>Max value:</b> " + max.value()); } else if (annObj instanceof Version) { entityConstraintModel.setRules("Entity version; For Multi-Version control"); } else if (annObj instanceof DataType) { DataType dataType = (DataType) annObj; String typeClass = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeClass = dataType.actualClassName(); } entityConstraintModel.setRules("<b>Type:</b> " + typeClass); } else { entityConstraintModel.setRules(annotation.toString()); } //Annotations that have related classes if (annObj instanceof DataType) { DataType dataType = (DataType) annObj; entityConstraintModel.getRelatedClasses().add(dataType.value().getSimpleName()); } if (annObj instanceof FK) { FK fk = (FK) annObj; entityConstraintModel.getRelatedClasses().add(fk.value().getSimpleName()); } if (annObj instanceof ValidValueType) { ValidValueType validValueType = (ValidValueType) annObj; for (Class lookupClass : validValueType.lookupClass()) { entityConstraintModel.getRelatedClasses().add(lookupClass.getSimpleName()); } StringBuilder sb = new StringBuilder(); for (Class enumClass : validValueType.enumClass()) { sb.append("<br>"); sb.append(enumClass.getSimpleName()).append(": ("); sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")"); } entityConstraintModel .setRules(entityConstraintModel.getRules() + " " + sb.toString()); } fieldModel.getConstraints().add(entityConstraintModel); } } docModel.getFieldModels().add(fieldModel); } } addFields(entity.getSuperclass(), docModel); } }
From source file:org.apromore.test.heuristic.JavaBeanHeuristic.java
/** * Checks that a Javabean matches a set of rules in terms of its structure and behaviour. Given a class representing a Javabean, run the following * checks. <ol> <li>The class has a public no-arg constructor</li> <li>For each field declared in the class, a public getter and setter * exists</li> <li>Set the value using the setter, then ensure that the getter returns the same object</li> </ol> * * @param clazz the class to check.// w w w .java 2s. com * @param excludes any field names that should be excluded from the check. */ public void checkJavaBeanProperties(Class clazz, String... excludes) { Field[] fields = clazz.getDeclaredFields(); Object bean = newInstance(clazz); List<String> excludeList = Arrays.asList(excludes); for (Field field : fields) { if (excludeList.contains(field.getName())) { continue; } int modifiers = field.getModifiers(); if (!(Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers))) { processField(field, bean); } } }