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:cz.cuni.mff.d3s.tools.perfdoc.server.measuring.codegen.CodeGenerator.java

private void makeAndCompileMeasurementCode(BenchmarkSetting setting) throws CompileException, IOException {

    MethodReflectionInfo mrInfo = (MethodReflectionInfo) setting.getTestedMethod();
    Method testedMethod = mrInfo.getMethod();
    MeasurementQuality measurementQuality = setting.getMeasurementQuality();

    VelocityContext context = new VelocityContext();

    context.put("priority", measurementQuality.getPriority());
    context.put("warmupTime", measurementQuality.getWarmupTime());
    context.put("warmupCycles", measurementQuality.getNumberOfWarmupCycles());
    context.put("measurementCycles", measurementQuality.getNumberOfMeasurementsCycles());
    context.put("measurementTime", measurementQuality.getMeasurementTime());

    String pathToMainDir = System.getProperty("user.dir");
    String pathToDir = pathToMainDir + File.separator
            + getDirectory().replaceAll("/", Matcher.quoteReplacement(File.separator)) + File.separator;
    context.put("directoryWhereToSaveResults", StringEscapeUtils.escapeJava(pathToDir));

    context.put("mClass", mrInfo.getContainingClass().getName());
    context.put("mFunctionIsStatic", Modifier.isStatic(testedMethod.getModifiers()));

    writeCode(context, templateMeasurementName);

    String javaClassDirectory = compiledClassDestinationDir + directoryName;
    String javaSourceName = javaDestinationDir + directoryName + "/" + templateMeasurementName + ".java";

    List<String> classPaths = getCompilationClassPaths();
    classPaths.add(javaClassDirectory);/*from   ww w . jav a 2s.  c o m*/

    Compiler.compile(javaSourceName, classPaths);
}

From source file:com.browseengine.bobo.serialize.JSONSerializer.java

public static JSONObject serializeJSONObject(JSONSerializable obj)
        throws JSONSerializationException, JSONException {
    if (obj instanceof JSONExternalizable) {
        return ((JSONExternalizable) obj).toJSON();
    }/*from   w  w  w.  java2s.c o  m*/

    JSONObject jsonObj = new JSONObject();
    Class clz = obj.getClass();
    Field[] fields = clz.getDeclaredFields();

    for (int i = 0; i < fields.length; ++i) {
        fields[i].setAccessible(true);
        int modifiers = fields[i].getModifiers();
        if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) {
            String name = fields[i].getName();
            Class type = fields[i].getType();

            try {
                Object value = fields[i].get(obj);

                if (type.isArray() && value != null) {
                    int len = Array.getLength(value);

                    Class cls = type.getComponentType();

                    JSONArray array = new JSONArray();

                    for (int k = 0; k < len; ++k) {
                        dumpObject(array, cls, value, k);
                    }
                    jsonObj.put(name, array);
                } else {
                    dumpObject(jsonObj, fields[i], obj);
                }
            } catch (Exception e) {
                throw new JSONSerializationException(e.getMessage(), e);
            }
        }
    }

    return jsonObj;
}

From source file:com.alibaba.rocketmq.common.MixAll.java

public static void printObjectProperties(final Logger log, final Object object,
        final boolean onlyImportantField) {
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            String name = field.getName();
            if (!name.startsWith("this")) {
                Object value = null;
                try {
                    field.setAccessible(true);
                    value = field.get(object);
                    if (null == value) {
                        value = "";
                    }//w ww  . ja v  a2s  .  c om
                } catch (IllegalArgumentException e) {
                    System.out.println(e);
                } catch (IllegalAccessException e) {
                    System.out.println(e);
                }

                if (onlyImportantField) {
                    Annotation annotation = field.getAnnotation(ImportantField.class);
                    if (null == annotation) {
                        continue;
                    }
                }

                if (log != null) {
                    log.info(name + "=" + value);
                } else {
                    System.out.println(name + "=" + value);
                }
            }
        }
    }
}

From source file:com.px100systems.util.serialization.SerializationDefinition.java

private SerializationDefinition(Class<?> cls) {
    definitions.put(cls, this);

    if (cls.getName().startsWith("java"))
        throw new RuntimeException("System classes are not supported: " + cls.getSimpleName());

    try {// w  ww.jav a2s .co  m
        constructor = cls.getConstructor();
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("Missing no-arg constructor: " + cls.getSimpleName());
    }

    serializingSetter = ReflectionUtils.findMethod(cls, "setSerializing", boolean.class);

    for (Class<?> c = cls; c != null && !c.equals(Object.class); c = c.getSuperclass()) {
        for (Field field : c.getDeclaredFields()) {
            if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()))
                continue;

            FieldDefinition fd = new FieldDefinition();
            fd.name = field.getName();

            fd.type = field.getType();
            if (fd.type.isPrimitive())
                throw new RuntimeException("Primitives are not supported: " + fd.type.getSimpleName());

            Calculated calc = field.getAnnotation(Calculated.class);

            if (!fd.type.equals(Integer.class) && !fd.type.equals(Long.class) && !fd.type.equals(Double.class)
                    && !fd.type.equals(Boolean.class) && !fd.type.equals(Date.class)
                    && !fd.type.equals(String.class))
                if (fd.type.equals(List.class) || fd.type.equals(Set.class)) {
                    SerializedCollection sc = field.getAnnotation(SerializedCollection.class);
                    if (sc == null)
                        throw new RuntimeException(
                                cls.getSimpleName() + "." + fd.name + " is missing @SerializedCollection");

                    if (calc != null)
                        throw new RuntimeException(cls.getSimpleName() + "." + fd.name
                                + " cannot have a calculator because it is a collection");

                    fd.collectionType = sc.type();
                    fd.primitive = fd.collectionType.equals(Integer.class)
                            || fd.collectionType.equals(Long.class) || fd.collectionType.equals(Double.class)
                            || fd.collectionType.equals(Boolean.class) || fd.collectionType.equals(Date.class)
                            || fd.collectionType.equals(String.class);
                    if (!fd.primitive) {
                        if (cls.getName().startsWith("java"))
                            throw new RuntimeException(cls.getSimpleName() + "." + fd.name
                                    + ": system collection types are not supported: "
                                    + fd.collectionType.getSimpleName());

                        if (!definitions.containsKey(fd.collectionType))
                            new SerializationDefinition(fd.collectionType);
                    }
                } else {
                    if (cls.getName().startsWith("java"))
                        throw new RuntimeException(
                                "System classes are not supported: " + fd.type.getSimpleName());

                    if (!definitions.containsKey(fd.type))
                        new SerializationDefinition(fd.type);
                }
            else
                fd.primitive = true;

            try {
                fd.accessor = c.getMethod(PropertyAccessor.methodName("get", fd.name));
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing getter");
            }

            try {
                fd.mutator = c.getMethod(PropertyAccessor.methodName("set", fd.name), fd.type);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing setter");
            }

            if (calc != null)
                fd.calculator = new SpelExpressionParser().parseExpression(calc.value());

            fields.add(fd);
        }

        for (Method method : c.getDeclaredMethods())
            if (Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers())
                    && method.getName().startsWith("get")
                    && method.isAnnotationPresent(SerializedGetter.class)) {
                FieldDefinition fd = new FieldDefinition();
                fd.name = method.getName().substring(3);
                fd.name = fd.name.substring(0, 1).toLowerCase() + fd.name.substring(1);
                fd.type = method.getReturnType();
                fd.primitive = fd.type != null && (fd.type.equals(Integer.class) || fd.type.equals(Long.class)
                        || fd.type.equals(Double.class) || fd.type.equals(Boolean.class)
                        || fd.type.equals(Date.class) || fd.type.equals(String.class));

                if (!fd.primitive)
                    throw new RuntimeException("Not compact-serializable getter type: "
                            + (fd.type == null ? "void" : fd.type.getSimpleName()));

                fd.accessor = method;
                gettersOnly.add(fd);
            }
    }
}

From source file:py.una.pol.karaku.dao.entity.interceptors.InterceptorHandler.java

/**
 * Verifica si un field puede ser asignable. Se define un fiel asignable
 * como aquel que no es estatico, final.
 * /* w w w .  ja v a2  s .  c o  m*/
 * Como nota general tener en cuenta que un campo que no es String es
 * inmediatamente no asignable
 * 
 * @param field
 *            a ser evaluado
 * @return <code>true</code> si es asignable, <code>false</code> en caso
 *         contrario
 */
private boolean isAssignable(Field field) {

    int modifier = field.getModifiers();
    if (Modifier.isFinal(modifier)) {
        return false;
    }
    if (Modifier.isStatic(modifier)) {
        return false;
    }
    if (Modifier.isTransient(modifier)) {
        return false;
    }
    return field.getAnnotation(Transient.class) == null;
}

From source file:org.castor.jaxb.reflection.ClassInfoBuilder.java

/**
 * Checks if a field of a class is describeable or not e.g. static or
 * transient fields are not described./*ww  w. j a  v a  2 s. co  m*/
 * 
 * @param type
 *            the Class holding the field
 * @param field
 *            the field to check
 * @return true if the field should be described
 */
private boolean isDescribeable(final Class<?> type, final Field field) {
    boolean isDescribeable = true;
    Class<?> declaringClass = field.getDeclaringClass();
    if ((declaringClass != null) && !type.equals(declaringClass) && (!declaringClass.isInterface())) {
        isDescribeable = false;
    }
    if (Modifier.isStatic(field.getModifiers())) {
        isDescribeable &= false;
    }
    if (Modifier.isTransient(field.getModifiers())) {
        isDescribeable &= false;
    }
    if (field.isSynthetic()) {
        isDescribeable &= false;
    }
    return isDescribeable;
}

From source file:net.sf.ehcache.config.BeanHandler.java

/**
 * Finds a setter method./*w  w  w .  j a  v  a  2 s  . com*/
 */
private Method findSetMethod(final Class objClass, final String prefix, final String name) throws Exception {
    final String methodName = makeMethodName(prefix, name);
    final Method[] methods = objClass.getMethods();
    Method candidate = null;
    for (int i = 0; i < methods.length; i++) {
        final Method method = methods[i];
        if (!method.getName().equals(methodName)) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        if (method.getParameterTypes().length != 1) {
            continue;
        }
        if (!method.getReturnType().equals(Void.TYPE)) {
            continue;
        }
        if (candidate != null) {
            throw new Exception("Multiple " + methodName + "() methods in class " + objClass.getName() + ".");
        }
        candidate = method;
    }

    return candidate;
}

From source file:HashCodeBuilder.java

/**
 * This method uses reflection to build a valid hash code. 
 * <p>/* w ww . java  2  s  . c  o  m*/
 * It uses Field.setAccessible to gain access to private fields. This means
 * that it will throw a security exception if run under a security manger, if
 * the permissions are not set up.
 * It is also not as efficient as testing explicitly. 
 * If the TestTransients parameter is set to true, transient members will be
 * tested, otherwise they are ignored, as they are likely derived fields, and
 * not part of the value of the object. 
 * Static fields will not be tested.
 * <p>
 * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally
 * these should be different for each class, however this is not vital.
 * Prime numbers are preferred, especially for the multiplier.
 * 
 * @param initialNonZeroOddNumber
 * @param multiplierNonZeroOddNumber
 * @param object  the object to create a hash code for
 * @param testTransients  whether to include transient fields
 * @return int hash code
 * @throws IllegalArgumentException if the object is null
 * @throws IllegalArgumentException if the number is zero or even
 */
public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object,
        boolean testTransients) {

    if (object == null) {
        throw new IllegalArgumentException("The object to build a hash code for must not be null");
    }
    HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber);
    Field[] fields = object.getClass().getDeclaredFields();
    Field.setAccessible(fields, true);
    for (int i = 0; i < fields.length; ++i) {
        Field f = fields[i];
        if (testTransients || !Modifier.isTransient(f.getModifiers())) {
            if (!Modifier.isStatic(f.getModifiers())) {
                try {
                    hashCodeBuilder.append(f.get(object));
                } catch (IllegalAccessException e) {
                    //this can't happen. Would get a Security exception instead
                    //throw a runtime exception in case the impossible happens.
                    throw new InternalError("Unexpected IllegalAccessException");
                }
            }
        }
    }
    return hashCodeBuilder.toHashCode();
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ??//from w ww. jav a2 s  .co m
 * @param context 
 * @param requestClass class??class??????
 * @param requestParams ??null????????
 * @return ?
 */
@SuppressWarnings("unchecked")
public static RequestParams parseRequestParams(Context context, Class<? extends Request> requestClass,
        RequestParams requestParams) {
    if (requestParams == null) {
        requestParams = new RequestParams();
    }

    String requestParamName;
    String requestParamValue;
    Object requestParamValueObject = null;
    for (Field field : getFields(requestClass, true, true, true)) {
        // ???????
        if (!field.isAnnotationPresent(Param.class) || !Modifier.isStatic(field.getModifiers())) {
            continue;
        }

        // ????
        requestParamName = parseParamAnnotation(context, field);
        if (requestParamName == null) {
            requestParamName = field.getName();
        }

        // ?ValueValue?
        if (field.isAnnotationPresent(Value.class)) {
            String value = parseValueAnnotation(context, field);
            if (value != null) {
                requestParams.put(requestParamName, value);
                continue;
            }
        }

        try {
            field.setAccessible(true);
            requestParamValueObject = field.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // ?null?
        if (requestParamValueObject == null) {
            continue;
        }

        // ?Map???
        if (Map.class.isAssignableFrom(field.getType())) {
            for (java.util.Map.Entry<Object, Object> entry : ((Map<Object, Object>) requestParamValueObject)
                    .entrySet()) {
                if (entry.getKey() != null && entry.getValue() != null) {
                    String key = entry.getKey().toString();
                    String value = entry.getValue().toString();
                    if (key != null && !"".equals(key) && value != null && !"".equals(value)) {
                        requestParams.put(key, value);
                    }
                }
            }
            continue;
        }

        // ?File?
        if (File.class.isAssignableFrom(field.getType())) {
            try {
                requestParams.put(requestParamName, (File) requestParamValueObject);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            continue;
        }

        // ?ArrayListArrayList?
        if (ArrayList.class.isAssignableFrom(field.getType())) {
            requestParams.put(requestParamName, (ArrayList<String>) requestParamValueObject);
            continue;
        }

        // ?boolean
        if (Boolean.class.isAssignableFrom(field.getType())) {
            if ((Boolean) requestParamValueObject) {
                requestParamValue = parseTrueAnnotation(context, field);
                if (requestParamValue == null) {
                    requestParamValue = DEFAULT_VALUE_TRUE;
                }
            } else {
                requestParamValue = parseFalseAnnotation(context, field);
                if (requestParamValue == null) {
                    requestParamValue = DEFAULT_VALUE_FALSE;
                }
            }
            requestParams.put(requestParamName, requestParamValue);
            continue;
        }

        // ?
        if (Enum.class.isAssignableFrom(field.getType())) {
            Enum<?> enumObject = (Enum<?>) requestParamValueObject;
            requestParamValue = parseValueAnnotationFromEnum(context, enumObject);
            if (requestParamValue == null) {
                requestParamValue = enumObject.name();
            }
            requestParams.put(requestParamName, requestParamValue);
            continue;
        }

        // ???
        requestParamValue = requestParamValueObject.toString();
        if (requestParamValue != null && !"".equals(requestParamValue)) {
            requestParams.put(requestParamName, requestParamValue);
        }
    }

    return requestParams;
}

From source file:microsoft.exchange.webservices.data.core.service.schema.ServiceObjectSchema.java

/**
 * Adds the schema property names to dictionary.
 *
 * @param type                   The type.
 * @param propertyNameDictionary The property name dictionary.
 *///from   w w  w .  j  a v a 2 s .  com
protected static void addSchemaPropertyNamesToDictionary(Class<?> type,
        Map<PropertyDefinition, String> propertyNameDictionary) {

    Field[] fields = type.getDeclaredFields();
    for (Field field : fields) {
        int modifier = field.getModifiers();
        if (Modifier.isPublic(modifier) && Modifier.isStatic(modifier)) {
            Object o;
            try {
                o = field.get(null);
                if (o instanceof PropertyDefinition) {
                    PropertyDefinition propertyDefinition = (PropertyDefinition) o;
                    propertyNameDictionary.put(propertyDefinition, field.getName());
                }
            } catch (IllegalArgumentException e) {
                LOG.error(e);

                // Skip the field
            } catch (IllegalAccessException e) {
                LOG.error(e);

                // Skip the field
            }
        }
    }
}