Example usage for java.lang.reflect Field getModifiers

List of usage examples for java.lang.reflect Field getModifiers

Introduction

In this page you can find the example usage for java.lang.reflect Field getModifiers.

Prototype

public int getModifiers() 

Source Link

Document

Returns the Java language modifiers for the field represented by this Field object, as an integer.

Usage

From source file:org.apache.openaz.xacml.std.json.JSONRequest.java

/**
 * Use reflection to load the map with all the names of all DataTypes, both the long name and the
 * shorthand, and point each name to the appropriate Identifier. The shorthand map is used differently in
 * JSONRequest than in JSONResponse, so there are similarities and differences in the implementation. This
 * is done once the first time a Request is processed.
 *//*ww  w.j  a v a  2s  . c  o m*/
private static void initShorthandMap() throws JSONStructureException {
    Field[] declaredFields = XACML3.class.getDeclaredFields();
    shorthandMap = new HashMap<String, Identifier>();
    for (Field field : declaredFields) {
        if (Modifier.isStatic(field.getModifiers()) && field.getName().startsWith("ID_DATATYPE")
                && Modifier.isPublic(field.getModifiers())) {
            try {
                Identifier id = (Identifier) field.get(null);
                String longName = id.stringValue();
                // most names start with 'http://www.w3.org/2001/XMLSchema#'
                int sharpIndex = longName.lastIndexOf("#");
                if (sharpIndex <= 0) {
                    // some names start with 'urn:oasis:names:tc:xacml:1.0:data-type:'
                    // or urn:oasis:names:tc:xacml:2.0:data-type:
                    if (longName.contains(":data-type:")) {
                        sharpIndex = longName.lastIndexOf(":");
                    } else {
                        continue;
                    }
                }
                String shortName = longName.substring(sharpIndex + 1);
                // put both the full name and the short name in the table
                shorthandMap.put(longName, id);
                shorthandMap.put(shortName, id);
            } catch (Exception e) {
                throw new JSONStructureException("Error loading ID Table, e=" + e);
            }
        }
    }
}

From source file:RevEngAPI.java

/** Generate a .java file for the outline of the given class. */
public void doClass(Class c) throws IOException {
    className = c.getName();//from   ww w.  java 2s  . c o  m
    // pre-compute offset for stripping package name
    classNameOffset = className.lastIndexOf('.') + 1;

    // Inner class
    if (className.indexOf('$') != -1)
        return;

    // get name, as String, with . changed to /
    String slashName = className.replace('.', '/');
    String fileName = slashName + ".java";

    System.out.println(className + " --> " + fileName);

    String dirName = slashName.substring(0, slashName.lastIndexOf("/"));
    new File(dirName).mkdirs();

    // create the file.
    PrintWriter out = new PrintWriter(new FileWriter(fileName));

    out.println("// Generated by RevEngAPI for class " + className);

    // If in a package, say so.
    Package pkg;
    if ((pkg = c.getPackage()) != null) {
        out.println("package " + pkg.getName() + ';');
        out.println();
    }
    // print class header
    int cMods = c.getModifiers();
    printMods(cMods, out);
    out.print("class ");
    out.print(trim(c.getName()));
    out.print(' ');
    // XXX get superclass 
    out.println('{');

    // print constructors
    Constructor[] ctors = c.getDeclaredConstructors();
    for (int i = 0; i < ctors.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Constructors");
        }
        Constructor cons = ctors[i];
        int mods = cons.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(cons.getName()) + "(");
        Class[] classes = cons.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.print("\t}");
    }

    // print method names
    Method[] mems = c.getDeclaredMethods();
    for (int i = 0; i < mems.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Methods");
        }
        Method m = mems[i];
        if (m.getName().startsWith("access$"))
            continue;
        int mods = m.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(m.getReturnType());
        out.print(' ');
        out.print(trim(m.getName()) + "(");
        Class[] classes = m.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.println("\treturn " + defaultValue(m.getReturnType()) + ';');
        out.println("\t}");
    }

    // print fields
    Field[] flds = c.getDeclaredFields();
    for (int i = 0; i < flds.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Fields");
        }
        Field f = flds[i];
        int mods = f.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(f.getType().getName()));
        out.print(' ');
        out.print(f.getName());
        if (Modifier.isFinal(mods)) {
            try {
                out.print(" = " + f.get(null));
            } catch (IllegalAccessException ex) {
                out.print("; // " + ex.toString());
            }
        }
        out.println(';');
    }
    out.println("}");
    //out.flush();
    out.close();
}

From source file:cn.webwheel.ActionSetter.java

public List<SetterInfo> parseSetters(Class cls) {
    List<SetterInfo> list = new ArrayList<SetterInfo>();
    Field[] fields = cls.getFields();
    for (int i = fields.length - 1; i >= 0; i--) {
        Field field = fields[i];
        if (Modifier.isFinal(field.getModifiers()))
            continue;
        if (Modifier.isStatic(field.getModifiers()))
            continue;
        WebParam param = field.getAnnotation(WebParam.class);
        String name = field.getName();
        if (field.getType().isArray())
            name += "[]";
        if (param != null && !param.value().isEmpty())
            name = param.value();/*from   w  w  w .j  a  v  a  2s.  c om*/
        SetterInfo si = getSetterInfo(field, name);
        if (si == null) {
            if (param != null) {
                logger.severe("wrong WebParam used at " + field);
            }
            continue;
        }
        list.add(si);
    }

    Method[] methods = cls.getMethods();
    for (int i = methods.length - 1; i >= 0; i--) {
        Method method = methods[i];
        WebParam param = method.getAnnotation(WebParam.class);
        String name = isSetter(method);
        if (name == null) {
            continue;
        }
        if (method.getParameterTypes()[0].isArray()) {
            name += "[]";
        }
        if (param != null && !param.value().isEmpty()) {
            name = param.value();
        }
        SetterInfo si = getSetterInfo(method, name);
        if (si == null) {
            if (param != null) {
                logger.severe("wrong WebParam used at " + method);
            }
            continue;
        }
        list.add(si);
    }
    return list;
}

From source file:com.ryan.ryanreader.jsonwrap.JsonBufferedObject.java

public void populateObject(final Object o) throws InterruptedException, IOException, IllegalArgumentException,
        InstantiationException, NoSuchMethodException, InvocationTargetException {

    if (join() != Status.LOADED) {
        throwFailReasonException();/*from w  w  w  .  j  a v  a2 s  . c om*/
    }

    final Field[] objectFields = o.getClass().getFields();

    try {

        for (final Field objectField : objectFields) {

            if ((objectField.getModifiers() & Modifier.TRANSIENT) != 0) {
                continue;
            }

            final JsonValue val;

            if (properties.containsKey(objectField.getName())) {
                val = properties.get(objectField.getName());

            } else if (objectField.getName().startsWith("_json_")) {
                val = properties.get(objectField.getName().substring("_json_".length()));
            } else {
                val = null;
            }

            if (val == null) {
                continue;
            }

            objectField.setAccessible(true);

            final Class<?> fieldType = objectField.getType();

            if (fieldType == Long.class || fieldType == Long.TYPE) {
                objectField.set(o, val.asLong());

            } else if (fieldType == Double.class || fieldType == Double.TYPE) {
                objectField.set(o, val.asDouble());

            } else if (fieldType == Integer.class || fieldType == Integer.TYPE) {
                objectField.set(o, val.isNull() ? null : val.asLong().intValue());

            } else if (fieldType == Float.class || fieldType == Float.TYPE) {
                objectField.set(o, val.isNull() ? null : val.asDouble().floatValue());

            } else if (fieldType == Boolean.class || fieldType == Boolean.TYPE) {
                objectField.set(o, val.asBoolean());

            } else if (fieldType == String.class) {
                objectField.set(o, val.asString());

            } else if (fieldType == JsonBufferedArray.class) {
                objectField.set(o, val.asArray());

            } else if (fieldType == JsonBufferedObject.class) {
                objectField.set(o, val.asObject());

            } else if (fieldType == JsonValue.class) {
                objectField.set(o, val);

            } else if (fieldType == Object.class) {

                final Object result;

                switch (val.getType()) {
                case BOOLEAN:
                    result = val.asBoolean();
                    break;
                case INTEGER:
                    result = val.asLong();
                    break;
                case STRING:
                    result = val.asString();
                    break;
                case FLOAT:
                    result = val.asDouble();
                    break;
                default:
                    result = val;
                }

                objectField.set(o, result);

            } else {
                objectField.set(o, val.asObject(fieldType));
            }
        }

    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.quantumbadger.redreader.jsonwrap.JsonBufferedObject.java

public void populateObject(final Object o) throws InterruptedException, IOException, IllegalArgumentException,
        InstantiationException, NoSuchMethodException, InvocationTargetException {

    if (join() != STATUS_LOADED) {
        throwFailReasonException();//from   w w w . j a v a2  s .  com
    }

    final Field[] objectFields = o.getClass().getFields();

    try {

        for (final Field objectField : objectFields) {

            if ((objectField.getModifiers() & Modifier.TRANSIENT) != 0) {
                continue;
            }

            final JsonValue val;

            if (properties.containsKey(objectField.getName())) {
                val = properties.get(objectField.getName());

            } else if (objectField.getName().startsWith("_json_")) {
                val = properties.get(objectField.getName().substring("_json_".length()));
            } else {
                val = null;
            }

            if (val == null) {
                continue;
            }

            objectField.setAccessible(true);

            final Class<?> fieldType = objectField.getType();

            if (fieldType == Long.class || fieldType == Long.TYPE) {
                objectField.set(o, val.asLong());

            } else if (fieldType == Double.class || fieldType == Double.TYPE) {
                objectField.set(o, val.asDouble());

            } else if (fieldType == Integer.class || fieldType == Integer.TYPE) {
                objectField.set(o, val.isNull() ? null : val.asLong().intValue());

            } else if (fieldType == Float.class || fieldType == Float.TYPE) {
                objectField.set(o, val.isNull() ? null : val.asDouble().floatValue());

            } else if (fieldType == Boolean.class || fieldType == Boolean.TYPE) {
                objectField.set(o, val.asBoolean());

            } else if (fieldType == String.class) {
                objectField.set(o, val.asString());

            } else if (fieldType == JsonBufferedArray.class) {
                objectField.set(o, val.asArray());

            } else if (fieldType == JsonBufferedObject.class) {
                objectField.set(o, val.asObject());

            } else if (fieldType == JsonValue.class) {
                objectField.set(o, val);

            } else if (fieldType == Object.class) {

                final Object result;

                switch (val.getType()) {
                case JsonValue.TYPE_BOOLEAN:
                    result = val.asBoolean();
                    break;
                case JsonValue.TYPE_INTEGER:
                    result = val.asLong();
                    break;
                case JsonValue.TYPE_STRING:
                    result = val.asString();
                    break;
                case JsonValue.TYPE_FLOAT:
                    result = val.asDouble();
                    break;
                default:
                    result = val;
                }

                objectField.set(o, result);

            } else {
                objectField.set(o, val.asObject(fieldType));
            }
        }

    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.threewks.thundr.bigmetrics.service.BigMetricsServiceImpl.java

protected Map<Field, FieldProcessor<?>> findFieldProcessors(Class<?> eventClass) {
    List<Field> fields = Arrays.asList(ReflectUtil.getSupportedFields(eventClass, Object.class));
    Map<Field, FieldProcessor<?>> processors = new LinkedHashMap<>();
    for (Field field : fields) {
        if (!field.isSynthetic() && !Modifier.isTransient(field.getModifiers())
                && !field.isAnnotationPresent(Ignore.class)) {
            field.setAccessible(true);//from  w w w  .j a v a 2 s . c om
            FieldProcessor<?> processor = determineProcessor(field);
            processors.put(field, processor);
        }
    }
    return processors;
}

From source file:org.alex73.skarynka.scan.Book2.java

private void get(Object obj, String prefix, List<String> lines) throws Exception {
    for (Field f : obj.getClass().getFields()) {
        if (Modifier.isPublic(f.getModifiers()) && !Modifier.isStatic(f.getModifiers())
                && !Modifier.isTransient(f.getModifiers())) {
            if (f.getType() == int.class) {
                int v = f.getInt(obj);
                if (v != -1) {
                    lines.add(prefix + f.getName() + "=" + v);
                }//from   www.j a v  a2 s .  c o  m
            } else if (f.getType() == boolean.class) {
                lines.add(prefix + f.getName() + "=" + f.getBoolean(obj));
            } else if (f.getType() == String.class) {
                String s = (String) f.get(obj);
                if (s != null) {
                    lines.add(prefix + f.getName() + "=" + s);
                }
            } else if (Set.class.isAssignableFrom(f.getType())) {
                Set<?> set = (Set<?>) f.get(obj);
                StringBuilder t = new StringBuilder();
                for (Object o : set) {
                    t.append(o.toString()).append(';');
                }
                if (t.length() > 0) {
                    t.setLength(t.length() - 1);
                }
                lines.add(prefix + f.getName() + "=" + t);
            } else {
                throw new RuntimeException("Unknown field class for get '" + f.getName() + "'");
            }
        }
    }
}

From source file:com.googlecode.ehcache.annotations.key.AbstractDeepCacheKeyGenerator.java

/**
 * Calls {@link #shouldReflect(Object)} to determine if the object needs to be reflected on to
 * generate a good key. If so {@link AccessibleObject#setAccessible(AccessibleObject[], boolean)} is
 * used to enable access to private, protected and default fields. Each non-transient, non-static field
 * has {@link #deepHashCode(Object, Object)} called on it.
 *//*from w ww  .  j  a  va 2s .  c  o m*/
protected final void reflectionDeepHashCode(G generator, final Object element) {
    //Special objects which shouldn't be reflected on due to lack of interesting fields
    if (element instanceof Class<?>) {
        this.append(generator, element);
        return;
    }

    //Determine if the element should be reflected on
    if (!this.shouldReflect(element)) {
        this.append(generator, element);
        return;
    }

    //Accumulate the data that makes up the object being reflected on so it can be recursed on as a single grouping of data
    final List<Object> reflectiveObject = new LinkedList<Object>();

    //Write out the target class so that two classes with the same fields can't collide
    reflectiveObject.add(element.getClass());

    try {
        for (Class<?> targetClass = element.getClass(); targetClass != null; targetClass = targetClass
                .getSuperclass()) {
            final Field[] fields = targetClass.getDeclaredFields();
            AccessibleObject.setAccessible(fields, true);

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

                //Ignore static and transient fields
                if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
                    final Object fieldValue = field.get(element);
                    reflectiveObject.add(fieldValue);
                }
            }
        }
    } catch (IllegalAccessException exception) {
        ReflectionUtils.handleReflectionException(exception);
    }

    this.deepHashCode(generator, reflectiveObject);
}

From source file:org.alex73.skarynka.scan.Book2.java

private void set(Object obj, String fieldName, String value, String debug) {
    try {//  ww  w .  java  2s  .  co m
        Field f = obj.getClass().getField(fieldName);
        if (!Modifier.isPublic(f.getModifiers()) || Modifier.isStatic(f.getModifiers())
                || Modifier.isTransient(f.getModifiers())) {
            errors.add("Field is not public for '" + debug + "'");
            return;
        }
        if (f.getType() == int.class) {
            f.setInt(obj, Integer.parseInt(value));
        } else if (f.getType() == boolean.class) {
            f.setBoolean(obj, Boolean.parseBoolean(value));
        } else if (f.getType() == String.class) {
            f.set(obj, value);
        } else if (Set.class.isAssignableFrom(f.getType())) {
            TreeSet<String> v = new TreeSet<>(Arrays.asList(value.split(";")));
            f.set(obj, v);
        } else {
            errors.add("Unknown field class for set '" + debug + "'");
            return;
        }
    } catch (NoSuchFieldException ex) {
        errors.add("Unknown field for set '" + debug + "'");
    } catch (IllegalAccessException ex) {
        errors.add("Wrong field for set '" + debug + "'");
    } catch (Exception ex) {
        errors.add("Error set value to field for '" + debug + "'");
    }
}

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

private ConfigClassInfo(Class<?> clazz) throws InstantiationException, IllegalAccessException {
    _clazz = clazz;//from   w w  w  . j av  a  2 s . c o  m
    _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();
    }
}