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:tools.xor.util.ClassUtil.java

/** 
 * Invoke the given method as a privileged action, if necessary. 
 * @param target the object on which the method needs to be invoked
 * @param field we are reading or writing
 * @param value to set in the field//from   w w w  . j  ava 2 s .c  om
 * @param read true if this a read operation
 * @return result of the invocation
 * @throws InvocationTargetException while invoking the method
 * @throws IllegalAccessException when accessing the meta data
 */
public static Object invokeFieldAsPrivileged(final Object target, final Field field, final Object value,
        final boolean read) throws InvocationTargetException, IllegalAccessException {

    if (Modifier.isPublic(field.getModifiers())) {
        Object readValue = null;
        if (read)
            readValue = field.get(target);
        else
            field.set(target, value);
        return readValue;
    } else {
        return AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                field.setAccessible(true);
                Object readValue = null;
                try {
                    if (read)
                        readValue = field.get(target);
                    else
                        field.set(target, value);
                } catch (Exception e) {
                    throw wrapRun(e);
                }
                return readValue;
            }
        });
    }
}

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:com.phoenixnap.oss.ramlapisync.naming.SchemaHelper.java

/**
 * Breaks down a class into component fields which are mapped as Query Parameters. If Javadoc is supplied, this will
 * be injected as comments/*from   w w  w.ja  v  a2 s .c  om*/
 * 
 * @param param The Parameter representing the class to be converted into query parameters
 * @param javaDocStore The associated JavaDoc (if any)
 * @return a Map of Parameter RAML models keyed by parameter name
 */
public static Map<String, QueryParameter> convertClassToQueryParameters(final Parameter param,
        final JavaDocStore javaDocStore) {
    final Map<String, QueryParameter> outParams = new TreeMap<>();

    if (param == null || param.equals(Void.class)) {
        return outParams;
    }
    final ApiParameterMetadata parameterMetadata = new ApiParameterMetadata(param);

    if (mapSimpleType(param.getType()) != null) {
        throw new IllegalArgumentException(
                "This method should only be called on non primitive classes which will be broken down into query parameters");
    }

    try {
        for (Field field : param.getType().getDeclaredFields()) {
            if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())
                    && !java.lang.reflect.Modifier.isTransient(field.getModifiers())
                    && !java.lang.reflect.Modifier.isVolatile(field.getModifiers())) {
                QueryParameter queryParam = new QueryParameter();

                // Check if we have comments
                JavaDocEntry paramComment = javaDocStore == null ? null
                        : javaDocStore.getJavaDoc(field.getName());
                if (paramComment != null && StringUtils.hasText(paramComment.getComment())) {
                    queryParam.setDescription(paramComment.getComment());
                }

                // Populate parameter model with data such as name, type and
                // required/not
                queryParam.setDisplayName(field.getName());
                ParamType simpleType = mapSimpleType(field.getType());
                queryParam.setType(simpleType == null ? ParamType.STRING : simpleType);
                queryParam.setRequired(parameterMetadata.isNullable());
                queryParam.setRepeat(false); // TODO we could add validation
                // info
                // here - maybe hook into
                // JSR303
                // annotations
                outParams.put(field.getName(), queryParam);
            }
        }
        return outParams;

    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:net.sf.jasperreports.engine.query.JRHibernateQueryExecuter.java

private static final Type loadTypeConstant(Class<?> typeConstantsClass, String name) {
    try {/*w w w. ja  v a 2  s. c o  m*/
        Field constant = typeConstantsClass.getField(name);
        if (!Modifier.isStatic(constant.getModifiers()) || !Type.class.isAssignableFrom(constant.getType())) {
            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_UNRESOLVED_TYPE_CONSTANT,
                    new Object[] { name, typeConstantsClass.getName() });
        }
        Type type = (Type) constant.get(null);
        return type;
    } catch (NoSuchFieldException e) {
        throw new JRRuntimeException(e);
    } catch (SecurityException e) {
        throw new JRRuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new JRRuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new JRRuntimeException(e);
    }
}

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

/**
 * ??Properties//from  w  w w .j  a v a 2  s  .c om
 */
public static Properties object2Properties(final Object object) {
    Properties properties = new Properties();

    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);
                } catch (IllegalArgumentException e) {
                    System.out.println(e);
                } catch (IllegalAccessException e) {
                    System.out.println(e);
                }

                if (value != null) {
                    properties.setProperty(name, value.toString());
                }
            }
        }
    }

    return properties;
}

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 = "";
                    }/*  ww w. jav  a 2 s.c  o  m*/
                } 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:Main.java

public static Collection<Field> getDeepDeclaredFields(Class<?> c) {
    if (_reflectedFields.containsKey(c)) {
        return _reflectedFields.get(c);
    }//from  w ww .  j  ava  2  s.c o  m
    Collection<Field> fields = new ArrayList<Field>();
    Class<?> curr = c;

    while (curr != null) {
        try {
            Field[] local = curr.getDeclaredFields();

            for (Field field : local) {
                if (!field.isAccessible()) {
                    try {
                        field.setAccessible(true);
                    } catch (Exception ignored) {
                    }
                }

                int modifiers = field.getModifiers();
                if (!Modifier.isStatic(modifiers) && !field.getName().startsWith("this$")
                        && !Modifier.isTransient(modifiers)) {
                    fields.add(field);
                }
            }
        } catch (ThreadDeath t) {
            throw t;
        } catch (Throwable ignored) {
        }

        curr = curr.getSuperclass();
    }
    _reflectedFields.put(c, fields);
    return fields;
}

From source file:net.sf.keystore_explorer.crypto.jcepolicy.JcePolicyUtil.java

/**
 * Hack to disable crypto restrictions until Java 9 is out.
 *
 * See http://stackoverflow.com/a/22492582/2672392
 *//*from w  w  w.  j a va 2s .c  om*/
public static void removeRestrictions() {
    try {
        Class<?> jceSecurityClass = Class.forName("javax.crypto.JceSecurity");
        Class<?> cryptoPermissionsClass = Class.forName("javax.crypto.CryptoPermissions");
        Class<?> cryptoAllPermissionClass = Class.forName("javax.crypto.CryptoAllPermission");

        Field isRestrictedField = jceSecurityClass.getDeclaredField("isRestricted");
        isRestrictedField.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
        isRestrictedField.set(null, false);

        Field defaultPolicyField = jceSecurityClass.getDeclaredField("defaultPolicy");
        defaultPolicyField.setAccessible(true);
        PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);

        Field permsField = cryptoPermissionsClass.getDeclaredField("perms");
        permsField.setAccessible(true);
        ((Map<?, ?>) permsField.get(defaultPolicy)).clear();

        Field cryptoAllPermissionInstanceField = cryptoAllPermissionClass.getDeclaredField("INSTANCE");
        cryptoAllPermissionInstanceField.setAccessible(true);
        defaultPolicy.add((Permission) cryptoAllPermissionInstanceField.get(null));
    } catch (Exception e) {
        // ignore
    }
}

From source file:lapin.load.Loader.java

static private Object _impSymbols(Class clazz, Object export, Env env) throws IllegalAccessException {
    Lisp lisp = env.lisp();/*from w  w w  . jav a2s.co m*/
    Field[] fields = clazz.getFields();
    Class symClass = Symbol.class;
    for (int i = 0; i < fields.length; i++) {
        Field f = fields[i];
        int m = f.getModifiers();
        if (!Modifier.isStatic(m))
            continue;
        if (!symClass.isAssignableFrom(f.getType()))
            continue;
        Symbol sym = Data.symbol(f.get(null));
        lisp.getObarray().imp(sym.pkg(), sym);
        if (!Data.isNot(export))
            lisp.getObarray().exp(sym.pkg(), sym);
    }
    return Symbols.T;
}

From source file:lapin.load.Loader.java

static private Object _impSubrs(Object pkgname, Class clazz, Symbol indicator, Object export, Env env)
        throws IllegalAccessException {
    Lisp lisp = env.lisp();/*from   w  w  w  .  j  av  a  2 s.  co m*/
    Field[] fields = clazz.getFields();
    Class subrClass = Subr.class;
    for (int i = 0; i < fields.length; i++) {
        Field f = fields[i];
        int m = f.getModifiers();
        if (!Modifier.isStatic(m))
            continue;
        if (!subrClass.isAssignableFrom(f.getType()))
            continue;
        Subr subr = Data.subr(f.get(null));
        Symbol sym = Data.symbol(lisp.getObarray().intern(pkgname, subr.name()).nth(0));
        if (!Data.isNot(export))
            lisp.getObarray().exp(pkgname, sym);
        Object old = lisp.getProp(sym, indicator, Symbols.NIL);
        if (!Data.isNot(old))
            throw new LispException(
                    "conflict detected while importing subrs " + "defined in ~S: name=~S indicator=~S",
                    Lists.list(clazz, sym, indicator));
        lisp.setProp(sym, indicator, subr);
        if (subr instanceof Prop)
            lisp.setProp((Prop) subr, SysSymbols.SUBR_FIELD, f);
    }
    return Symbols.T;
}