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:org.assertj.assertions.generator.util.ClassUtil.java

private static boolean isNotStaticPublicField(Field field) {
    final int modifiers = field.getModifiers();
    return !Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers);
}

From source file:org.apache.nifi.processors.kafka.pubsub.KafkaProcessorUtils.java

private static Set<String> getPublicStaticStringFieldValues(final Class<?>... classes) {
    final Set<String> strings = new HashSet<>();
    for (final Class<?> classType : classes) {
        for (final Field field : classType.getDeclaredFields()) {
            if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())
                    && field.getType().equals(String.class)) {
                try {
                    strings.add(String.valueOf(field.get(null)));
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    //ignore
                }//www  .  ja  v  a 2s .  c  o  m
            }
        }
    }
    return strings;
}

From source file:name.yumaa.ChromeLogger4J.java

/**
 * Converts an object to a better format for logging
 * @param object    variable to conver// w  w  w.j  ava  2  s . com
 * @param depth     recursion depth
 * @return converted object, ready to put to JSON
 */
private Object convert(Object object, int depth) {
    // *** return simple types as is ***
    if (object == null || object instanceof String || object instanceof Number || object instanceof Boolean)
        return object;

    // *** other simple types ***

    if (object instanceof Character || object instanceof StringBuffer || object instanceof StringBuilder
            || object instanceof Currency || object instanceof Date || object instanceof Locale)
        return object.toString();

    if (object instanceof Calendar)
        return ((Calendar) object).getTime().toString();

    if (object instanceof SimpleDateFormat)
        return ((SimpleDateFormat) object).toPattern();

    // check recursion depth
    if (depth > this.depth)
        return "d>" + this.depth;

    // mark this object as processed so we don't convert it twice and it
    // also avoid recursion when objects refer to each other
    processed.add(object);

    // *** not so simple types, but we can foreach it ***

    if (object instanceof Map) {
        JSONObject jobject = new JSONObject();
        for (Object key : ((Map<Object, Object>) object).keySet()) {
            Object value = ((Map<Object, Object>) object).get(key);
            addValue(jobject, key.toString(), value, depth);
        }
        return jobject;
    }

    if (object instanceof Collection) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Collection<Object>) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    if (object instanceof Iterable) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Iterable<Object>) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    if (object instanceof Object[]) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Object[]) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    // *** object of unknown type ***

    JSONObject jobject = new JSONObject();

    Class<?> cls = object.getClass();
    jobject.put("___class_name", cls.getName()); // add the class name
    jobject.put("___toString()", object.toString()); // and to string representation

    if (!this.reflect)
        return jobject;

    // get all properties using reflection
    if (this.reflectfields) {
        try {
            for (Field field : cls.getDeclaredFields()) {
                Boolean access = field.isAccessible();
                field.setAccessible(true);

                int mod = field.getModifiers();
                String key = getKey(mod, field.getName());
                Object value;
                try {
                    value = field.get(object);
                } catch (Exception e) {
                    value = e.toString();
                }

                field.setAccessible(access);

                if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod)))
                    continue;
                if (!this.reflectstatic && Modifier.isStatic(mod))
                    continue;

                addValue(jobject, key, value, depth);
            }
        } catch (SecurityException e) {
        }
    }

    // get all methods using reflection
    if (this.reflectmethods) {
        try {
            JSONObject methods = new JSONObject();
            for (Method method : cls.getDeclaredMethods()) {
                Boolean access = method.isAccessible();
                method.setAccessible(true);

                Class<?>[] params = method.getParameterTypes();
                StringBuilder parameters = new StringBuilder("");
                for (int i = 0, j = params.length; i < j; i++) {
                    parameters.append(params[i].getName());
                    if (i + 1 < j)
                        parameters.append(", ");
                }
                int mod = method.getModifiers();
                String key = getKey(mod, method.getName() + "(" + parameters.toString() + ")");
                String value = method.getReturnType().getName();

                method.setAccessible(access);

                if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod)))
                    continue;
                if (!this.reflectstatic && Modifier.isStatic(mod))
                    continue;

                methods.put(key, value);
            }
            jobject.put("___methods", methods);
        } catch (SecurityException e) {
        }
    }

    return jobject;
}

From source file:cern.c2mon.shared.common.datatag.address.impl.HardwareAddressImpl.java

@Override
public final int hashCode() {

    int result = 0;

    Field[] fields = this.getClass().getDeclaredFields();

    for (Field field : fields) {
        // compare non-final, non-static and non-transient fields only
        if (!Modifier.isFinal(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())
                && !Modifier.isTransient(field.getModifiers())) {
            try {

                // skip arrays
                if (!field.getType().isArray() && field.get(this) != null) {
                    // for string take its length
                    if (field.getType().equals(String.class)) {
                        result ^= ((String) field.get(this)).length();
                    } else if (field.getType().equals(short.class) || field.getType().equals(Short.class)) {
                        result ^= field.getShort(this);
                    } else if (field.getType().equals(int.class) || field.getType().equals(Integer.class)) {
                        result ^= field.getInt(this);
                    } else if (field.getType().equals(float.class) || field.getType().equals(Float.class)) {
                        result ^= (int) field.getFloat(this);
                    } else if (field.getType().equals(double.class) || field.getType().equals(Double.class)) {
                        result ^= (int) field.getDouble(this);
                    } else if (field.getType().equals(long.class) || field.getType().equals(Long.class)) {
                        result ^= (int) field.getLong(this);
                    } else if (field.getType().equals(byte.class) || field.getType().equals(Byte.class)) {
                        result ^= field.getByte(this);
                    } else if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) {
                        result ^= field.getBoolean(this) == Boolean.TRUE ? 1 : 0;
                    }/*w  w w.j  a v  a2 s.c om*/
                }
            } catch (Exception e) {
                log.error(e.toString());
                throw new RuntimeException("Exception caught while calculating HardwareAddress hashcode.", e);
            }
        }
    }
    return result;
}

From source file:ReflectUtil.java

/**
 * Looks for an instance (i.e. non-static) public field with the matching name and
 * returns it if one exists.  If no such field exists, returns null.
 *
 * @param clazz the clazz who's fields to examine
 * @param property the name of the property/field to look for
 * @return the Field object or null if no matching field exists
 *///from www . j a  v a 2s  .  c  o m
public static Field getField(Class<?> clazz, String property) {
    try {
        Field field = clazz.getField(property);
        return !Modifier.isStatic(field.getModifiers()) ? field : null;
    } catch (NoSuchFieldException nsfe) {
        return null;
    }
}

From source file:org.apache.brooklyn.core.catalog.internal.CatalogClasspathDo.java

/** removes inner classes (non-static nesteds) and others; 
 * bear in mind named ones will be hard to instantiate without the outer class instance) */
private <T> Iterable<Class<? extends T>> excludeInvalidClasses(Iterable<Class<? extends T>> input) {
    Predicate<Class<? extends T>> f = new Predicate<Class<? extends T>>() {
        @Override/*from  ww w .  j a  va 2  s.c o m*/
        public boolean apply(@Nullable Class<? extends T> input) {
            if (input == null)
                return false;
            if (input.isLocalClass() || input.isAnonymousClass())
                return false;
            if (Modifier.isAbstract(input.getModifiers())) {
                if (input.getAnnotation(ImplementedBy.class) == null)
                    return false;
            }
            // non-abstract top-level classes are okay
            if (!input.isMemberClass())
                return true;
            if (!Modifier.isStatic(input.getModifiers()))
                return false;
            // nested classes only okay if static
            return true;
        }
    };
    return Iterables.filter(input, f);
}

From source file:com.oembedler.moon.graphql.engine.dfs.GraphQLSchemaDfsTraversal.java

public GraphQLFieldDefinition getFieldDefinition(DfsContext dfsContext, Class<?> implClass, Field field) {

    GraphQLFieldDefinition graphQLFieldDefinition = null;
    ResolvableTypeAccessor resolvableTypeAccessor = ResolvableTypeAccessor.forField(field, implClass);

    if (resolvableTypeAccessor.isNotIgnorable()) {
        GraphQLOutputType graphQLOutputType = (GraphQLOutputType) createGraphQLFieldType(dfsContext,
                resolvableTypeAccessor, true);
        GraphQLFieldDefinition.Builder graphQLFieldDefinitionBuilder = GraphQLFieldDefinition
                .newFieldDefinition().name(resolvableTypeAccessor.getName()).type(graphQLOutputType)
                .deprecate(resolvableTypeAccessor.getGraphQLDeprecationReason())
                .description(resolvableTypeAccessor.getDescription());

        boolean isConstant = Modifier.isFinal(field.getModifiers()) && Modifier.isStatic(field.getModifiers());
        if (isConstant) {
            graphQLFieldDefinitionBuilder
                    .staticValue(org.springframework.util.ReflectionUtils.getField(field, null));
        }//from  w ww  .  j  a  va2s .  c  o m
        graphQLFieldDefinition = graphQLFieldDefinitionBuilder.build();
        addToFieldDefinitionResolverMap(dfsContext, graphQLFieldDefinition,
                resolvableTypeAccessor.getGraphQLComplexitySpelExpression());
    }

    return graphQLFieldDefinition;
}

From source file:net.minecraftforge.fml.common.FMLModContainer.java

@SuppressWarnings("unchecked")
private Method gatherAnnotations(Class<?> clazz) throws Exception {
    Method factoryMethod = null;/*from  w  w w .ja va 2 s . c  om*/
    for (Method m : clazz.getDeclaredMethods()) {
        for (Annotation a : m.getAnnotations()) {
            if (a.annotationType().equals(Mod.EventHandler.class)) {
                if (m.getParameterTypes().length == 1
                        && FMLEvent.class.isAssignableFrom(m.getParameterTypes()[0])) {
                    m.setAccessible(true);
                    eventMethods.put((Class<? extends FMLEvent>) m.getParameterTypes()[0], m);
                } else {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The mod %s appears to have an invalid event annotation %s. This annotation can only apply to methods with recognized event arguments - it will not be called",
                            getModId(), a.annotationType().getSimpleName());
                }
            } else if (a.annotationType().equals(Mod.InstanceFactory.class)) {
                if (Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0
                        && factoryMethod == null) {
                    m.setAccessible(true);
                    factoryMethod = m;
                } else if (!(Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0)) {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on %s(%s)",
                            m.getName(), Arrays.asList(m.getParameterTypes()));
                } else if (factoryMethod != null) {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The InstanceFactory annotation can only be used once, the application to %s(%s) will be ignored",
                            m.getName(), Arrays.asList(m.getParameterTypes()));
                }
            }
        }
    }
    return factoryMethod;
}

From source file:com.twinsoft.convertigo.beans.CheckBeans.java

private static void analyzeJavaClass(String javaClassName) {
    try {//from  www  . ja v  a2  s.com
        Class<?> javaClass = Class.forName(javaClassName);
        String javaClassSimpleName = javaClass.getSimpleName();

        if (!DatabaseObject.class.isAssignableFrom(javaClass)) {
            //Error.NON_DATABASE_OBJECT.add(javaClassName);
            return;
        }

        nBeanClass++;

        String dboBeanInfoClassName = javaClassName + "BeanInfo";
        MySimpleBeanInfo dboBeanInfo = null;
        try {
            dboBeanInfo = (MySimpleBeanInfo) (Class.forName(dboBeanInfoClassName)).newInstance();
        } catch (ClassNotFoundException e) {
            if (!Modifier.isAbstract(javaClass.getModifiers())) {
                Error.MISSING_BEAN_INFO
                        .add(javaClassName + " (expected bean info: " + dboBeanInfoClassName + ")");
            }
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        BeanDescriptor beanDescriptor = dboBeanInfo.getBeanDescriptor();

        // Check abstract class
        if (Modifier.isAbstract(javaClass.getModifiers())) {
            // Check icon (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check icon (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check display name
            if (!beanDescriptor.getDisplayName().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (!beanDescriptor.getShortDescription().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DESCRIPTION.add(javaClassName);
            }
        } else {
            nBeanClassNotAbstract++;

            // Check bean declaration in database_objects.xml
            if (!dboXmlDeclaredDatabaseObjects.contains(javaClassName)) {
                Error.BEAN_DEFINED_BUT_NOT_USED.add(javaClassName);
            }

            // Check icon name policy (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            String expectedIconName = javaClassName.replace(javaClassSimpleName,
                    "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_16x16";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (16x16)
            File iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check icon name policy (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_32x32";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (32x32)
            iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check display name
            if (beanDescriptor.getDisplayName().equals("?")) {
                Error.BEAN_MISSING_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (beanDescriptor.getShortDescription().equals("?")) {
                Error.BEAN_MISSING_DESCRIPTION.add(javaClassName);
            }
        }

        // Check declared bean properties
        PropertyDescriptor[] propertyDescriptors = dboBeanInfo.getLocalPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propertyName = propertyDescriptor.getName();
            try {
                javaClass.getDeclaredField(propertyName);
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                try {
                    // Try to find it in the upper classes
                    javaClass.getField(propertyName);
                } catch (SecurityException e1) {
                    // printStackTrace();
                } catch (NoSuchFieldException e1) {
                    Error.PROPERTY_DECLARED_BUT_NOT_FOUND.add(javaClassName + ": " + propertyName);
                }
            }
        }

        Method[] methods = javaClass.getDeclaredMethods();
        List<Method> listMethods = Arrays.asList(methods);
        List<String> listMethodNames = new ArrayList<String>();
        for (Method method : listMethods) {
            listMethodNames.add(method.getName());
        }

        Field[] fields = javaClass.getDeclaredFields();

        for (Field field : fields) {
            int fieldModifiers = field.getModifiers();

            // Ignore static fields (constants)
            if (Modifier.isStatic(fieldModifiers))
                continue;

            String fieldName = field.getName();

            String errorMessage = javaClassName + ": " + field.getName();

            // Check bean info
            PropertyDescriptor propertyDescriptor = isBeanProperty(fieldName, dboBeanInfo);
            if (propertyDescriptor != null) {
                // Check bean property name policy
                if (!propertyDescriptor.getName().equals(fieldName)) {
                    Error.PROPERTY_NAMING_POLICY.add(errorMessage);
                }

                String declaredGetter = propertyDescriptor.getReadMethod().getName();
                String declaredSetter = propertyDescriptor.getWriteMethod().getName();

                String formattedFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
                String expectedGetter = "get" + formattedFieldName;
                String expectedSetter = "set" + formattedFieldName;

                // Check getter name policy
                if (!declaredGetter.equals(expectedGetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared getter: " + declaredGetter + "\n"
                                    + "      Expected getter: " + expectedGetter);
                }

                // Check setter name policy
                if (!declaredSetter.equals(expectedSetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared setter: " + declaredSetter + "\n"
                                    + "      Expected setter: " + expectedSetter);
                }

                // Check required private modifiers for bean property
                if (!Modifier.isPrivate(fieldModifiers)) {
                    Error.PROPERTY_NOT_PRIVATE.add(errorMessage);
                }

                // Check getter
                if (!listMethodNames.contains(declaredGetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared getter not found: " + declaredGetter);
                }

                // Check setter
                if (!listMethodNames.contains(declaredSetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared setter not found: " + declaredGetter);
                }

                // Check non transient modifier
                if (Modifier.isTransient(fieldModifiers)) {
                    Error.PROPERTY_TRANSIENT.add(errorMessage);
                }
            } else if (!Modifier.isTransient(fieldModifiers)) {
                Error.FIELD_NOT_TRANSIENT.add(errorMessage);
            }
        }
    } catch (ClassNotFoundException e) {
        System.out.println("ERROR on " + javaClassName);
        e.printStackTrace();
    }
}

From source file:cn.org.awcp.core.mybatis.mapper.EntityHelper.java

/**
 * ?Field/*  ww w .j  a va  2  s. c  o m*/
 * 
 * @param entityClass
 * @param fieldList
 * @return
 */
private static List<Field> getAllField(Class<?> entityClass, List<Field> fieldList) {
    if (fieldList == null) {
        fieldList = new ArrayList<Field>();
    }
    if (entityClass.equals(Object.class)) {
        return fieldList;
    }
    Field[] fields = entityClass.getDeclaredFields();
    for (Field field : fields) {
        // ??bug#2
        if (!Modifier.isStatic(field.getModifiers())) {
            fieldList.add(field);
        }
    }
    if (entityClass.getSuperclass() != null && !entityClass.getSuperclass().equals(Object.class)
            && !Map.class.isAssignableFrom(entityClass.getSuperclass())
            && !Collection.class.isAssignableFrom(entityClass.getSuperclass())) {
        return getAllField(entityClass.getSuperclass(), fieldList);
    }
    return fieldList;
}