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:Mopex.java

/**
 * Returns an array of fields that are the declared instance variables of
 * cls. An instance variable is a field that is not static.
 * //  w w w .  j ava  2  s  .com
 * @return java.lang.reflect.Field[]
 * @param cls
 *            java.lang.Class
 */
//start extract getDeclaredIVS
public static Field[] getDeclaredIVs(Class cls) {
    Field[] fields = cls.getDeclaredFields();
    // Count the IVs
    int numberOfIVs = 0;
    for (int i = 0; i < fields.length; i++) {
        if (!Modifier.isStatic(fields[i].getModifiers()))
            numberOfIVs++;
    }
    Field[] declaredIVs = new Field[numberOfIVs];
    // Populate declaredIVs
    int j = 0;
    for (int i = 0; i < fields.length; i++) {
        if (!Modifier.isStatic(fields[i].getModifiers()))
            declaredIVs[j++] = fields[i];
    }
    return declaredIVs;
}

From source file:cop.raml.mocks.MockUtils.java

public static ExecutableElementMock createExecutable(Method method) {
    if (method == null)
        return null;

    boolean isStatic = Modifier.isStatic(method.getModifiers());
    String params = Arrays.stream(method.getParameterTypes()).map(Class::getSimpleName)
            .collect(Collectors.joining(","));
    String name = String.format("(%s)%s", params, method.getReturnType().getSimpleName());

    return new ExecutableElementMock(method.getName() + "()", createMethodElement(name).asType())
            .setStatic(isStatic).setSimpleName(method.getName());
}

From source file:com.hortonworks.registries.common.util.ReflectionHelper.java

/**
 * Given a class, this method returns a map of names of all the instance (non static) fields to type.
 * if the class has any super class it also includes those fields.
 * @param clazz , not null/*from  w  w  w .  java 2  s.  co  m*/
 * @return
 */
public static Map<String, Class> getFieldNamesToTypes(Class clazz) {
    Field[] declaredFields = clazz.getDeclaredFields();
    Map<String, Class> instanceVariableNamesToTypes = new HashMap<>();
    for (Field field : declaredFields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            LOG.trace("clazz {} has field {} with type {}", clazz.getName(), field.getName(),
                    field.getType().getName());
            instanceVariableNamesToTypes.put(field.getName(), field.getType());
        } else {
            LOG.trace("clazz {} has field {} with type {}, which is static so ignoring", clazz.getName(),
                    field.getName(), field.getType().getName());
        }
    }

    if (!clazz.getSuperclass().equals(Object.class)) {
        instanceVariableNamesToTypes.putAll(getFieldNamesToTypes(clazz.getSuperclass()));
    }
    return instanceVariableNamesToTypes;
}

From source file:catchla.yep.loader.ObjectCursorLoader.java

@SuppressWarnings("TryWithIdenticalCatches")
@NonNull//from   ww w.ja v  a  2s . c om
private ObjectCursor.CursorIndices<T> createIndices(final Cursor cursor) {
    if (mIndicesClass.isMemberClass() && !Modifier.isStatic(mIndicesClass.getModifiers())) {
        throw new IllegalArgumentException("Indices class must be static");
    }
    try {
        return mIndicesClass.getConstructor(Cursor.class).newInstance(cursor);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.trafficspaces.api.model.Resource.java

public JSONObject getJSONObject() {
    JSONObject jsonObject = new JSONObject();
    Field[] fields = this.getClass().getFields();
    try {//from www  . j av a  2 s.  com
        for (int i = 0; i < fields.length; i++) {

            Object fieldValue = fields[i].get(this);
            int fieldModifiers = fields[i].getModifiers();
            //System.out.println("name=" + fields[i].getName() + ", value=" + fieldValue + ", type=" +fields[i].getType() + 
            //      ", ispublic="+Modifier.isPublic(fieldModifiers) + ", isstatic="+Modifier.isStatic(fieldModifiers) + ", isnative="+Modifier.isNative(fieldModifiers));
            if (fieldValue != null && Modifier.isPublic(fieldModifiers) && !Modifier.isStatic(fieldModifiers)
                    && !Modifier.isNative(fieldModifiers)) {

                String name = fields[i].getName();
                Class type = fields[i].getType();

                if (type.isPrimitive()) {
                    if (type.equals(int.class)) {
                        jsonObject.put(name, fields[i].getInt(this));
                    } else if (type.equals(double.class)) {
                        jsonObject.put(name, fields[i].getDouble(this));
                    }
                } else if (type.isArray()) {
                    JSONObject jsonSubObject = new JSONObject();
                    JSONArray jsonArray = new JSONArray();

                    jsonObject.put(name, jsonSubObject);
                    jsonSubObject.put(name.substring(0, name.length() - 1), jsonArray);

                    Object[] values = (Object[]) fieldValue;
                    for (int j = 0; j < values.length; j++) {
                        if (values[j] != null && values[j] instanceof Resource) {
                            jsonArray.put(((Resource) values[j]).getJSONObject());
                        }
                    }
                } else if (Resource.class.isAssignableFrom(type)) {
                    jsonObject.put(name, ((Resource) fieldValue).getJSONObject());
                } else if (type.equals(String.class) && fieldValue != null) {
                    jsonObject.put(name, String.valueOf(fieldValue));
                }
            }
        }
    } catch (Exception nsfe) {
        //
    }
    return jsonObject;
}

From source file:ObjectAnalyzerTest.java

/**
 * Converts an object to a string representation that lists all fields.
 * /*  w w  w. ja  va 2  s.  c om*/
 * @param obj
 *          an object
 * @return a string with the object's class name and all field names and
 *         values
 */
public String toString(Object obj) {
    if (obj == null)
        return "null";
    if (visited.contains(obj))
        return "...";
    visited.add(obj);
    Class cl = obj.getClass();
    if (cl == String.class)
        return (String) obj;
    if (cl.isArray()) {
        String r = cl.getComponentType() + "[]{";
        for (int i = 0; i < Array.getLength(obj); i++) {
            if (i > 0)
                r += ",";
            Object val = Array.get(obj, i);
            if (cl.getComponentType().isPrimitive())
                r += val;
            else
                r += toString(val);
        }
        return r + "}";
    }

    String r = cl.getName();
    // inspect the fields of this class and all superclasses
    do {
        r += "[";
        Field[] fields = cl.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        // get the names and values of all fields
        for (Field f : fields) {
            if (!Modifier.isStatic(f.getModifiers())) {
                if (!r.endsWith("["))
                    r += ",";
                r += f.getName() + "=";
                try {
                    Class t = f.getType();
                    Object val = f.get(obj);
                    if (t.isPrimitive())
                        r += val;
                    else
                        r += toString(val);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        r += "]";
        cl = cl.getSuperclass();
    } while (cl != null);

    return r;
}

From source file:com.l2jfree.config.model.ConfigClassInfo.java

private ConfigClassInfo(Class<?> clazz) throws InstantiationException, IllegalAccessException {
    _clazz = clazz;/*  www .  j a  v  a2s  .  c om*/
    _configClass = _clazz.getAnnotation(ConfigClass.class);

    final Map<String, ConfigGroup> activeGroups = new FastMap<String, ConfigGroup>();

    for (Field field : _clazz.getFields()) {
        final ConfigField configField = field.getAnnotation(ConfigField.class);

        if (configField == null)
            continue;

        if (!Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
            _log.warn("Invalid modifiers for " + field);
            continue;
        }

        final ConfigFieldInfo info = new ConfigFieldInfo(field);

        _infos.add(info);

        if (info.getConfigGroupBeginning() != null) {
            final ConfigGroup group = new ConfigGroup();

            activeGroups.put(info.getConfigGroupBeginning().name(), group);

            info.setBeginningGroup(group);
        }

        for (ConfigGroup group : activeGroups.values())
            group.add(info);

        if (info.getConfigGroupEnding() != null) {
            final ConfigGroup group = activeGroups.remove(info.getConfigGroupEnding().name());

            info.setEndingGroup(group);
        }
    }

    if (!activeGroups.isEmpty())
        _log.warn("Invalid config grouping!");

    store();

    try {
        // just in case it's missing
        if (!getConfigFile().exists())
            store(getConfigFile(), null);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ai.general.net.MethodHandler.java

/**
 * The specified instance must be an instance of the class that defines the method or a
 * subclass of that class. It may be null for static methods.
 *
 * The method must be publicly accessible and it must be defined public in a class that is
 * public. If the method is defined in a nested class, both the nested class and the outer class
 * must be public./*  w w w  .  j a v a 2 s. c om*/
 *
 * Event methods must have exactly 1 parameter that accepts the publish or event data.
 * Any return values or exceptions thrown by an event method will be ignored.
 *
 * RPC call methods may have any number of parameters, return any value and throw exceptions.
 *
 * Method parameters must hava a POJO type. This includes primitive Java types or their arrays,
 * and bean types, i.e. classes that declare getters and setters for each field.
 *
 * @param name A unique name for the MethodHandler.
 * @param catchall True if this a catch-all handler.
 * @param instance Instance associated with method. May be null for static methods.
 * @param method The method to be called.
 * @throws IllegalArgumentException if the arguments are invalid or incompatible with each other.
 */
public MethodHandler(String name, boolean catchall, Object instance, Method method) {
    super(name, catchall);
    if (!Modifier.isStatic(method.getModifiers())) {
        if (instance == null) {
            throw new IllegalArgumentException("Non-static method requires instance.");
        }
        if (!method.getDeclaringClass().isInstance(instance)) {
            throw new IllegalArgumentException("Incompatible instance object.");
        }
    }
    this.instance_ = instance;
    this.method_ = method;
    parameter_types_ = method.getParameterTypes();
    json_parser_ = new ObjectMapper();
}

From source file:org.apache.pig.JVMReuseManager.java

public void registerForStaticDataCleanup(Class<?> clazz) {
    for (Method method : clazz.getMethods()) {
        if (method.isAnnotationPresent(StaticDataCleanup.class)) {
            if (!(Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers()))) {
                throw new RuntimeException("Method " + method.getName() + " in class " + clazz.getName()
                        + "should be public and static as it is annotated with  ");
            }/*w  w w  .  j a v a  2 s  . c o m*/
            LOG.debug("Method " + method.getName() + " in class " + method.getDeclaringClass()
                    + " registered for static data cleanup");
            instance.cleanupMethods.add(method);
        }
    }
}

From source file:net.buffalo.protocal.util.ClassUtil.java

private static HashMap getFieldMap(Class cl) {
    HashMap fieldMap = new HashMap();
    for (; cl != null; cl = cl.getSuperclass()) {
        Field[] fields = cl.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()))
                continue;
            field.setAccessible(true);//from w  ww .j  a v  a  2s.com
            fieldMap.put(field.getName(), field);
        }
    }

    return fieldMap;
}