Example usage for java.lang.reflect Modifier isStatic

List of usage examples for java.lang.reflect Modifier isStatic

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isStatic.

Prototype

public static boolean isStatic(int mod) 

Source Link

Document

Return true if the integer argument includes the static modifier, false otherwise.

Usage

From source file:com.sxj.mybatis.orm.builder.GenericStatementBuilder.java

public GenericStatementBuilder(Configuration configuration, final Class<?> entityClass) {
    super(configuration);
    this.entityClass = entityClass;
    sharded = ConfigurationProperties.isSharded(configuration);
    String resource = entityClass.getName().replace('.', '/') + ".java (best guess)";
    assistant = new MapperBuilderAssistant(configuration, resource);
    entity = entityClass.getAnnotation(Entity.class);
    mapperType = entity.mapper();//from   w w w . j a  v  a 2 s  . c  om

    if (!mapperType.isAssignableFrom(Void.class)) {
        namespace = mapperType.getName();
    } else {
        namespace = entityClass.getName();
    }
    assistant.setCurrentNamespace(namespace);
    Collection<String> cacheNames = configuration.getCacheNames();
    for (String name : cacheNames)
        if (namespace.equals(name)) {
            assistant.useCacheRef(name);
            break;
        }

    databaseId = super.getConfiguration().getDatabaseId();
    lang = super.getConfiguration().getDefaultScriptingLanuageInstance();

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Table table = entityClass.getAnnotation(Table.class);
    if (table == null) {
        tableName = CaseFormatUtils.camelToUnderScore(entityClass.getSimpleName());
    } else {
        tableName = table.name();
    }

    ///~~~~~~~~~~~~~~~~~~~~~~
    idField = AnnotationUtils.findDeclaredFieldWithAnnoation(Id.class, entityClass);
    if (!sharded && (this.idField.isAnnotationPresent(GeneratedValue.class))
            && (((GeneratedValue) this.idField.getAnnotation(GeneratedValue.class))
                    .strategy() == GenerationType.UUID))
        columnFields.add(idField);
    else
        columnFields.add(idField);
    versionField = AnnotationUtils.findDeclaredFieldWithAnnoation(Version.class, entityClass);

    ReflectionUtils.doWithFields(entityClass, new FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if (field.isAnnotationPresent(Column.class))
                columnFields.add(field);
            if (field.isAnnotationPresent(Sn.class))
                containSn = true;

        }
    }, new FieldFilter() {

        public boolean matches(Field field) {
            if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
                return false;
            }

            for (Annotation annotation : field.getAnnotations()) {
                if (Transient.class.isAssignableFrom(annotation.getClass())
                        || Id.class.isAssignableFrom(annotation.getClass())) {
                    return false;
                }
            }

            return true;
        }
    });
}

From source file:au.com.dw.testdatacapturej.reflection.MetadataGenerationHandler.java

/**
 * Use reflection to process the fields in an object. Iterates through the fields in the object
 * and passes them to the appropriate handlers.
 * //from   www .  j  ava2 s  .c  o  m
 * Note: does not handle static fields yet.
 * 
 * @param object
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
protected void handleFields(ObjectInfo info) throws IllegalArgumentException, IllegalAccessException {

    // use reflection to get the fields of the class
    Object object = info.getValue();
    Class<?> clazz = object.getClass();
    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);

    // check configuration for non-standard handling
    ConfigUtil configUtil = new ConfigUtil();

    // get list of field names that have been configured to have non-standard setter method generation
    List<String> ignoredSetterFieldNames = configUtil.getIgnoredSetters(info);

    // get list of collection field names for collection that are only accessed through adder methods
    List<CollectionAdderConfig> collectionConfigs = configUtil.getAddedCollections(info);

    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];

        int mod = field.getModifiers();

        // ignore static fields
        if (!Modifier.isStatic(mod)) {
            // get the field info
            String fieldName = field.getName();
            Object fieldValue = field.get(object);

            // create new ObjectInfo for the field object
            ObjectInfo fieldInfo = new ObjectInfo();
            fieldInfo.setFieldName(fieldName);
            fieldInfo.setValue(fieldValue);
            fieldInfo.setContainingClassFieldName(info.getClassFieldName());
            fieldInfo.getConstructorInfo().setHasDefaultConstructor(hasDefaultConstructor(fieldValue));

            // check if requires any special setter method generation
            if (ignoredSetterFieldNames != null) {
                if (ignoredSetterFieldNames.contains(fieldName)) {
                    fieldInfo.getSetterAdderInfo().setSetterGenerationType(SetterGenerationType.IGNORE);
                }
            }

            // determine type of field and pass to handler
            if (fieldValue != null) {
                if (!ReflectionUtil.hasSetterMethod(object, fieldName, fieldValue)) {
                    fieldInfo.getSetterAdderInfo().setHasSetter(false);
                }

                if (TypeUtil.isJavaClass(fieldValue)) {
                    fieldInfo.setType(ObjectType.SIMPLE);

                    fieldInfo.setClassName(fieldValue.getClass().getName());
                    fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null));
                } else if (TypeUtil.isArray(fieldValue)) {
                    fieldInfo.setType(ObjectType.ARRAY);

                    // special handling for array class names
                    fieldInfo.setClassName(ReflectionUtil.getArrayClassName(fieldValue));
                    String arrayType = fieldValue.getClass().getComponentType().getName();
                    fieldInfo.setClassFieldName(BuilderUtil.createArrayClassFieldName(arrayType, null, null));

                    if (!fieldInfo.isSetterIgnoreType()) {
                        handleArray(fieldInfo);
                    }
                } else if (TypeUtil.isCollection(fieldValue)) {
                    fieldInfo.setType(ObjectType.COLLECTION);

                    fieldInfo.setClassName(fieldValue.getClass().getName());
                    fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null));

                    // check if the collection field is only accessed through adder methods
                    // Note: the adder check overrides the ignored setter check if both are set
                    CollectionAdderConfig foundConfig = configUtil.getCollectionAdderConfig(collectionConfigs,
                            fieldName);

                    if (foundConfig != null) {
                        fieldInfo.getSetterAdderInfo().setUsesAdder(true);
                        fieldInfo.getSetterAdderInfo().setAdderMethodName(foundConfig.getAdderMethodName());

                        handleCollection(fieldInfo);
                    } else if (!fieldInfo.isSetterIgnoreType()) {
                        handleCollection(fieldInfo);
                    }
                } else if (TypeUtil.isMap(fieldValue)) {
                    fieldInfo.setType(ObjectType.MAP);

                    fieldInfo.setClassName(fieldValue.getClass().getName());
                    fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null));

                    if (!fieldInfo.isSetterIgnoreType()) {
                        handleMap(fieldInfo);
                    }
                } else {
                    fieldInfo.setType(ObjectType.OBJECT);

                    fieldInfo.setClassName(fieldValue.getClass().getName());
                    fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null));

                    if (!fieldInfo.isSetterIgnoreType()) {
                        handleFields(fieldInfo);
                    }
                }
            } else {
                // get class name from the Field if the field value is null
                fieldInfo.setClassName(ReflectionUtil.getClassNameFromField(field));
                fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(field, null, null));

                fieldInfo.setType(ObjectType.SIMPLE);
            }

            // check if configured parameterized constructor is to be used for the field
            fieldInfo.getConstructorInfo()
                    .addConstructorParamFieldNames(configUtil.getConstructionParameters(fieldInfo));

            // add the parent class to field class link
            fieldInfo.setParentInfo(info);
            info.addFieldToList(fieldInfo);
        }
    }
}

From source file:edu.wright.daselab.linkgen.ConfigurationParams.java

public final static boolean checkStatusOnLoad() throws Exception {
    // using reflection to check all properties/params fields.
    // you can use annotation for better retrieval
    // http://stackoverflow.com/questions/2020202/pitfalls-in-getting-member-variable-values-in-java-with-reflection
    // by this time, none of the values are empty.
    String name = "";
    String value = "";
    logger.info("Displaying all param values:");
    boolean isFine = true;
    Field[] fields = ConfigurationParams.class.getDeclaredFields();
    for (Field field : fields) {
        // check only final static fields
        if (!Modifier.isFinal((field.getModifiers())) || (!Modifier.isStatic(field.getModifiers()))) {
            continue;
        }/*  w  w w  .j a v a2s.  co  m*/
        name = field.getName();
        try {
            value = (String) field.get(null).toString();
        } catch (Exception e) {
            Monitor.error(Error.INVALID_CONFIG_PARAMS.toString());
            throw new IllegalArgumentException(Error.INVALID_CONFIG_PARAMS.toString());
        }
        if ((value == null) || value.toString().trim().equals("")) {
            isFine = false;
        }
        String status = isFine ? "OK" : "Failed";
        logger.info(status + " \t" + name + "=" + value);
        if (!isFine)
            throw new IllegalArgumentException(Error.INVALID_CONFIG_PARAMS.toString());
    }
    return isFine;
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Checks all of the classes in the serialization scope that implement
 * TetradSerializable to make sure all of their fields are either themselves
 * (a) primitive, (b) TetradSerializable, or (c) assignable from types
 * designated as safely serializable by virtue of being included in the
 * safelySerializableTypes array (see), or are arrays whose lowest order
 * component types satisfy either (a), (b), or (c). Safely serializable
 * classes in the Java API currently include collections classes, plus
 * String and Class. Collections classes are included, since their types
 * will be syntactically checkable in JDK 1.5. String and Class are members
 * of a broader type of Class whose safely can by checked by making sure
 * there is no way to pass into them via constructor or method argument any
 * object that is not TetradSerializable or safely serializable. But it's
 * easy enough now to just make a list.//from w ww  . ja v  a2  s . com
 *
 * @see #safelySerializableTypes
 */
public void checkNestingOfFields() {
    List classes = getAssignableClasses(new File(getSerializableScope()), TetradSerializable.class);

    boolean foundUnsafeField = false;

    for (Object aClass : classes) {
        Class clazz = (Class) aClass;

        if (TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
            continue;
        }

        Field[] fields = clazz.getDeclaredFields();

        FIELDS: for (Field field : fields) {
            //                System.out.println(field);

            if (Modifier.isTransient(field.getModifiers())) {
                continue;
            }

            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }

            Class type = field.getType();

            while (type.isArray()) {
                type = type.getComponentType();
            }

            if (type.isPrimitive()) {
                continue;
            }

            if (type.isEnum()) {
                continue;
            }

            //                // Printing out Collections fields temporarily.
            //                if (Collection.class.isAssignableFrom(type)) {
            //                    System.out.println("COLLECTION FIELD: " + field);
            //                }
            //
            //                if (Map.class.isAssignableFrom(type)) {
            //                    System.out.println("MAP FIELD: " + field);
            //                }

            if (TetradSerializable.class.isAssignableFrom(type)
                    && !TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
                continue;
            }

            for (Class safelySerializableClass : safelySerializableTypes) {
                if (safelySerializableClass.isAssignableFrom(type)) {
                    continue FIELDS;
                }
            }

            // A reference in an inner class to the outer class.
            if (field.getName().equals("this$0")) {
                continue;
            }

            System.out.println("UNSAFE FIELD:" + field);
            foundUnsafeField = true;
        }
    }

    if (foundUnsafeField) {
        throw new RuntimeException("Unsafe serializable fields found. Please " + "fix immediately.");
    }
}

From source file:org.testng.spring.test.AbstractDependencyInjectionSpringContextTests.java

private boolean isProtectedInstanceField(Field field) {
    int modifiers = field.getModifiers();
    return !Modifier.isStatic(modifiers) && Modifier.isProtected(modifiers);
}

From source file:adalid.core.Instance.java

private void finaliseFields() {
    String name;//from  w  ww. ja  v  a2  s .c  o m
    Class<?> type;
    int modifiers;
    boolean restricted;
    Object o;
    int depth = depth();
    int round = round();
    for (Field field : XS1.getFields(getClass(), Instance.class)) { // getClass().getDeclaredFields()
        field.setAccessible(true);
        logger.trace(field);
        name = field.getName();
        type = field.getType();
        if (!InstanceField.class.isAssignableFrom(type)) {
            continue;
        }
        modifiers = field.getModifiers();
        restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
        if (restricted) {
            continue;
        }
        String errmsg = "failed to initialize field \"" + field + "\" at " + this;
        try {
            o = field.get(this);
            if (o == null) {
                logger.debug(message(type, name, o, depth, round));
            } else if (o instanceof InstanceField) {
                finaliseInstanceField(field, (InstanceField) o);
            }
        } catch (IllegalArgumentException | IllegalAccessException ex) {
            logger.error(errmsg, ThrowableUtils.getCause(ex));
            TLC.getProject().getParser().increaseErrorCount();
        }
    }
}

From source file:org.apache.niolex.commons.reflect.FieldFilter.java

/**
 * Filter the fields with only static fields.
 *
 * @return this/*from  w w w .  j a v a2  s  . c om*/
 */
public final FieldFilter<FT> onlyStatic() {
    return this.add(new Filter() {
        @Override
        public boolean isValid(Field f) {
            return Modifier.isStatic(f.getModifiers());
        }
    });
}

From source file:com.cognifide.slice.mapper.GenericSlingMapper.java

/**
 * Returns true if a field can be assigned, i.e. is not final, nor static
 * /*from   ww w  .ja v  a2s. c  o m*/
 * @param field the field being investigated
 * @return true if the field is assignable, false otherwise
 */
private boolean isFieldAssignable(Field field) {
    int modifiers = field.getModifiers();
    if (Modifier.isFinal(modifiers)) {
        return false;
    } // else

    if (Modifier.isStatic(modifiers)) {
        return false;
    } // else
    return true;
}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static boolean isStatic(Method method) {
    return Modifier.isStatic(method.getModifiers());
}

From source file:com.qrmedia.commons.persistence.hibernate.clone.HibernateEntityBeanCloner.java

private static Collection<String> getPropertyNames(Collection<Method> methods) {
    Collection<String> methodNames = new ArrayList<String>();

    /*/* www  . j a  v  a 2s  .  com*/
     * If a method is an instance method, does not return void, takes no parameters 
     * and is named "get..." (it's assumed to be public), add the corresponding field name.
     */
    for (Method method : methods) {
        assert Modifier.isPublic(method.getModifiers()) : method;
        String methodName = method.getName();
        Matcher getterNameMatcher = GETTER_PREFIX.matcher(methodName);

        if (!Modifier.isStatic(method.getModifiers()) && (method.getReturnType() != Void.class)
                && (method.getParameterTypes().length == 0) && getterNameMatcher.matches()) {

            // the first group is the (uppercase) first letter of the field name
            methodNames.add(getterNameMatcher.replaceFirst(getterNameMatcher.group(1).toLowerCase() + "$2"));
        }

    }

    return methodNames;
}