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.hadoop.hive.ql.stats.TestStatsUtils.java

@Test
public void testPrimitiveSizeEstimations() throws Exception {
    HiveConf conf = new HiveConf();
    Set<String> exclusions = Sets.newHashSet();
    exclusions.add(serdeConstants.VOID_TYPE_NAME);
    exclusions.add(serdeConstants.LIST_TYPE_NAME);
    exclusions.add(serdeConstants.MAP_TYPE_NAME);
    exclusions.add(serdeConstants.STRUCT_TYPE_NAME);
    exclusions.add(serdeConstants.UNION_TYPE_NAME);
    Field[] serdeFields = serdeConstants.class.getFields();
    for (Field field : serdeFields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            continue;
        }/*from   ww w . j  a  va  2  s.c  om*/
        if (!field.getName().endsWith("_TYPE_NAME")) {
            continue;
        }
        String typeName = (String) FieldUtils.readStaticField(field);
        if (exclusions.contains(typeName)) {
            continue;
        }
        long siz = StatsUtils.getSizeOfPrimitiveTypeArraysFromType(typeName, 3, conf);
        assertNotEquals(field.toString(), 0, siz);
    }
}

From source file:io.github.huherto.springyRecords.BaseTable.java

public Number insert(R record) {

    Field[] fields = recordClass().getFields();
    String autoIncrementFieldName = null;
    if (autoIncrementField != null)
        autoIncrementFieldName = autoIncrementField.getName();
    Map<String, Object> parameters = new HashMap<String, Object>(fields.length);
    for (Field field : fields) {
        int mod = field.getModifiers();
        if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) {
            Column col = field.getAnnotation(Column.class);
            if (col != null && !field.getName().equals(autoIncrementFieldName)) {
                Object value;/*from   ww  w  . j av a 2s  .com*/
                try {
                    value = field.get(record);
                    parameters.put(col.name(), value);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    if (autoIncrementField != null)
        return insertCommand.executeAndReturnKey(parameters);
    insertCommand.execute(parameters);
    return null;
}

From source file:com.glaf.core.util.ReflectUtils.java

public static boolean isPublicInstanceField(Field field) {
    return Modifier.isPublic(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())
            && !Modifier.isFinal(field.getModifiers()) && !field.isSynthetic();
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * ???/*  w  w w .j  av  a  2 s.  co m*/
 * @return
 */
public static boolean removeCryptographyRestrictions() {
    if (!isRestrictedCryptography()) {
        return false;
    }
    try {
        /*
         * Do the following, but with reflection to bypass access checks:
         * 
         * JceSecurity.isRestricted = false;
         * JceSecurity.defaultPolicy.perms.clear();
         * JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
         */
        final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
        final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
        final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");

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

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

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

        final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
        instance.setAccessible(true);
        defaultPolicy.add((Permission) instance.get(null));
        return true;
    } catch (final Exception e) {
        LogUtil.error("Failed to remove cryptography restrictions", e);
        return false;
    }
}

From source file:com.activecq.api.ActiveProperties.java

/**
 * Uses reflection to create a List of the keys defined in the ActiveField subclass (and its inheritance tree).
 * Only fields that meet the following criteria are returned:
 * - public// w w w .  j  a  v a 2  s  .co  m
 * - static
 * - final
 * - String
 * - Upper case 
 * @return a List of all the Fields
 */
@SuppressWarnings("unchecked")
public List<String> getKeys() {
    ArrayList<String> keys = new ArrayList<String>();
    ArrayList<String> names = new ArrayList<String>();
    Class cls = this.getClass();

    if (cls == null) {
        return Collections.unmodifiableList(keys);
    }

    Field fieldList[] = cls.getFields();

    for (Field fld : fieldList) {
        int mod = fld.getModifiers();

        // Only look at public static final fields
        if (!Modifier.isPublic(mod) || !Modifier.isStatic(mod) || !Modifier.isFinal(mod)) {
            continue;
        }

        // Only look at String fields
        if (!String.class.equals(fld.getType())) {
            continue;
        }

        // Only look at uppercase fields
        if (!StringUtils.equals(fld.getName().toUpperCase(), fld.getName())) {
            continue;
        }

        // Get the value of the field
        String value;
        try {
            value = StringUtils.stripToNull((String) fld.get(this));
        } catch (IllegalArgumentException e) {
            continue;
        } catch (IllegalAccessException e) {
            continue;
        }

        // Do not add duplicate or null keys, or previously added named fields
        if (value == null || names.contains(fld.getName()) || keys.contains(value)) {
            continue;
        }

        // Success! Add key to key list
        keys.add(value);

        // Add field named to process field names list
        names.add(fld.getName());

    }

    return Collections.unmodifiableList(keys);
}

From source file:pl.maciejwalkowiak.plist.FieldSerializer.java

private String serializeField(Object o, Field field) {
    String result = "";

    int modifiers = field.getModifiers();

    if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) {
        ReflectionUtils.makeAccessible(field);

        if (!field.isAnnotationPresent(PlistIgnore.class)) {
            result = processField(field, o).toString();
        } else {// ww w.  j av a2s . c  o  m
            logger.debug("field {} is ignored", field.getName());
        }
    }

    return result;
}

From source file:adalid.core.XS1.java

static Field getField(boolean log, String role, String name, Class<?> type, Class<?> top,
        Class<?>... validTypes) {
    String string;/* www .  ja v  a 2  s .  c  om*/
    if (StringUtils.isBlank(role)) {
        string = "field role is missing or invalid";
        if (log) {
            logFieldErrorMessage(role, name, type, null, string);
        }
        return null;
    }
    if (StringUtils.isBlank(name)) {
        string = "field name is missing or invalid";
        if (log) {
            logFieldErrorMessage(role, name, type, null, string);
        }
        return null;
    }
    if (type == null) {
        string = "class is missing or invalid";
        if (log) {
            logFieldErrorMessage(role, name, type, null, string);
        }
        return null;
    }
    Field field = getField(name, type, top);
    if (field == null) {
        string = "field " + name + " not in class";
        if (log) {
            logFieldErrorMessage(role, name, type, field, string);
        }
        return null;
    }
    int modifiers = field.getModifiers();
    if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) {
        string = "field " + name + " has static and/or final modifier";
        if (log) {
            logFieldErrorMessage(role, name, type, field, string);
        }
        return null;
    }
    int length = validTypes == null ? 0 : validTypes.length;
    if (length < 1) {
        return field;
    }
    Class<?> ft = getTrueType(field.getType());
    String[] strings = new String[length];
    int i = 0;
    for (Class<?> vt : validTypes) {
        if (vt.isAssignableFrom(ft)) {
            return field;
        }
        strings[i++] = vt.getSimpleName();
    }
    string = "type of " + name + " is not " + StringUtils.join(strings, " or ");
    if (log) {
        logFieldErrorMessage(role, name, type, field, string);
    }
    return null;
}

From source file:com.googlecode.ddom.weaver.inject.InjectionPlugin.java

/**
 * Add the given binding. The binding will be configured with a {@link SingletonInjector} or a
 * {@link PrototypeInjector} depending on whether the injected class is a singleton as defined
 * in the Javadoc of the {@link SingletonInjector} class.
 * //from  ww w. j  a  v  a  2s .com
 * @param fieldType
 *            the target field type
 * @param injectedClass
 *            the injected class or <code>null</code> to inject a <code>null</code> value
 */
public <T> void addBinding(Class<T> fieldType, Class<? extends T> injectedClass) {
    Injector injector;
    if (injectedClass == null) {
        injector = null;
    } else {
        Field instanceField;
        try {
            Field candidateField = injectedClass.getField("INSTANCE");
            int modifiers = candidateField.getModifiers();
            // Note: getField only returns public fields, so no need to check for that
            // modifier here
            if (!Modifier.isStatic(modifiers) || !Modifier.isFinal(modifiers)) {
                if (log.isWarnEnabled()) {
                    log.warn("Ignoring public INSTANCE field in " + injectedClass.getName()
                            + " that is not static final");
                }
                instanceField = null;
            } else if (!fieldType.isAssignableFrom(candidateField.getType())) {
                if (log.isWarnEnabled()) {
                    log.warn("Ignoring INSTANCE field of incompatible type in " + injectedClass.getName());
                }
                instanceField = null;
            } else {
                instanceField = candidateField;
            }
        } catch (NoSuchFieldException ex) {
            instanceField = null;
        }
        if (instanceField != null) {
            injector = new SingletonInjector(injectedClass.getName(), instanceField.getType().getName());
        } else {
            injector = new PrototypeInjector(injectedClass.getName());
        }
    }
    addBinding(fieldType.getName(), injector);
}

From source file:org.apache.velocity.runtime.parser.node.SetPublicFieldExecutor.java

/**
 * @param clazz//from www . j a  v  a2  s  . co  m
 * @param property
 * @param arg
 */
protected void discover(final Class clazz, final String property, final Object arg) {
    try {
        Field field = introspector.getField(clazz, property);
        if (!Modifier.isFinal(field.getModifiers())) {
            setField(field);
        }
    }
    /**
     * pass through application level runtime exceptions
     */
    catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        String msg = "Exception while looking for public field '" + property;
        log.error(msg, e);
        throw new VelocityException(msg, e);
    }
}

From source file:org.nuxeo.client.internals.spi.NuxeoClientException.java

public String getRemoteStackTrace() {
    Field[] fields = this.getClass().getDeclaredFields();
    StringBuilder result = new StringBuilder();
    for (Field field : fields) {
        try {/*from   w  w  w .  j  a v a  2  s  . c o  m*/
            if (Modifier.isPrivate(field.getModifiers()) || field.get(this) == null) {
                continue;
            }
            result.append("  ");
            result.append(field.getName());
            result.append(": ");
            result.append(field.get(this));
        } catch (IllegalAccessException ex) {
            System.out.println(ex);
        }
        result.append(System.lineSeparator());
    }
    return result.toString();
}