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.axis.wsdl.fromJava.Types.java

/**
 * Write Enumeration Complex Type//from ww w .ja va  2  s  . co m
 * (Only supports enumeration classes of string types)
 *
 * @param qName QName of type.
 * @param cls   class of type
 * @return
 * @throws NoSuchMethodException
 * @throws IllegalAccessException
 * @throws AxisFault
 */
public Element writeEnumType(QName qName, Class cls)
        throws NoSuchMethodException, IllegalAccessException, AxisFault {

    if (!isEnumClass(cls)) {
        return null;
    }

    // Get the base type of the enum class
    java.lang.reflect.Method m = cls.getMethod("getValue", null);
    Class base = m.getReturnType();

    // Create simpleType, restriction elements
    Element simpleType = docHolder.createElement("simpleType");

    simpleType.setAttribute("name", qName.getLocalPart());

    Element restriction = docHolder.createElement("restriction");

    simpleType.appendChild(restriction);

    String baseType = writeType(base, null);

    restriction.setAttribute("base", baseType);

    // Create an enumeration using the field values
    Field[] fields = cls.getDeclaredFields();

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

        // Inspect each public static final field of the same type
        // as the base
        if (Modifier.isPublic(mod) && Modifier.isStatic(mod) && Modifier.isFinal(mod)
                && (field.getType() == base)) {

            // Create an enumeration using the value specified
            Element enumeration = docHolder.createElement("enumeration");

            enumeration.setAttribute("value", field.get(null).toString());
            restriction.appendChild(enumeration);
        }
    }

    return simpleType;
}

From source file:org.apache.hive.jdbc.TestJdbcWithMiniHS2.java

private void setReflectionUtilCache() {
    Field constructorCacheField;
    Cache<Class<?>, Constructor<?>> tmp;
    try {/*from w  ww .j a  v a2  s . c o  m*/
        constructorCacheField = ReflectionUtil.class.getDeclaredField("CONSTRUCTOR_CACHE");
        if (constructorCacheField != null) {
            constructorCacheField.setAccessible(true);
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(constructorCacheField,
                    constructorCacheField.getModifiers() & ~Modifier.FINAL);
            tmp = CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.SECONDS).concurrencyLevel(64)
                    .weakKeys().weakValues().build();
            constructorCacheField.set(tmp.getClass(), tmp);
        }
    } catch (Exception e) {
        System.out.println("Error when setting the CONSTRUCTOR_CACHE to expire: " + e);
    }
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.JsonRepresentedObject.java

private Object createChatPacket(String json) throws IllegalArgumentException, IllegalAccessException,
        InstantiationException, InvocationTargetException, NoSuchMethodException {
    if (nmsChatSerializerGsonInstance == null) {
        // Find the field and its value, completely bypassing obfuscation
        for (Field declaredField : Reflection.getNMSClass("ChatSerializer").getDeclaredFields()) {
            if (Modifier.isFinal(declaredField.getModifiers())
                    && Modifier.isStatic(declaredField.getModifiers())
                    && declaredField.getType().getName().endsWith("Gson")) {
                // We've found our field
                declaredField.setAccessible(true);
                nmsChatSerializerGsonInstance = declaredField.get(null);
                fromJsonMethod = nmsChatSerializerGsonInstance.getClass().getMethod("fromJson", String.class,
                        Class.class);
                break;
            }//from   www.  j a  va 2 s . co m
        }
    }

    // Since the method is so simple, and all the obfuscated methods have the same name, it's easier to reimplement 'IChatBaseComponent a(String)' than to reflectively call it
    // Of course, the implementation may change, but fuzzy matches might break with signature changes
    Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json,
            Reflection.getNMSClass("IChatBaseComponent"));

    return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent);
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Instantiates a new <code>FieldInfo</code> object as a column part of a
 * defined table./*from  ww  w. j  a  v  a 2  s. c o m*/
 *
 * @author vasu
 *
 * @param  tinfo the table info for the field
 * @param  field the non-<code>null</code> field to create an info object for
 * @throws IllegalArgumentException if unable to find a getter or setter
 *         method for the field of if improperly annotated
 */
FieldInfoImpl(TableInfoImpl<T> tinfo, Field field) {
    this.clazz = tinfo.getObjectClass();
    this.cinfo = (ClassInfoImpl<T>) tinfo.getClassInfo();
    this.tinfo = tinfo;
    this.declaringClass = field.getDeclaringClass();
    this.field = field;
    field.setAccessible(true); // make it accessible in case we need to
    this.isFinal = Modifier.isFinal(field.getModifiers());
    this.name = field.getName();
    this.type = DataTypeImpl.unwrapOptionalIfPresent(field.getType(), field.getGenericType());
    this.persisted = field.getAnnotation(Persisted.class);
    if (persisted != null) {
        org.apache.commons.lang3.Validate.isTrue(
                (persisted.as() != DataType.INFERRED) && !persisted.as().isCollection(),
                "@Persisted annotation cannot be of type '%s': %s.%s", persisted.as(), declaringClass.getName(),
                field.getName());
        this.persister = newPersister();
    } else {
        this.persister = null;
    }
    this.suffix = field.getAnnotation(SuffixKey.class);
    this.mandatory = field.getAnnotation(Mandatory.class) != null;
    final Map<String, Column> columns = ReflectionUtils.getAnnotationsByType(String.class, Column.class, field);
    final Map<String, Index> indexes = ReflectionUtils.getAnnotationsByType(String.class, Index.class, field);
    final Map<String, PartitionKey> partitionKeys = ReflectionUtils.getAnnotationsByType(String.class,
            PartitionKey.class, field);
    final Map<String, ClusteringKey> clusteringKeys = ReflectionUtils.getAnnotationsByType(String.class,
            ClusteringKey.class, field);
    final Map<String, TypeKey> typeKeys = ReflectionUtils.getAnnotationsByType(String.class, TypeKey.class,
            field);
    final boolean isInTable = tinfo.getTable() != null;

    if (isInTable) {
        org.apache.commons.lang3.Validate.isTrue(!(!indexes.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @Index: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(!partitionKeys.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @PartitionKey: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(!clusteringKeys.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @ClusteringKey: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(!typeKeys.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @TypeKey: %s.%s",
                declaringClass.getName(), field.getName());
    }
    // Note: while searching for the matching table, uses the name from the
    // table annotation instead of the one returned by getName() as the later
    // might have been cleaned and hence would not match what was defined in
    // the POJO
    final String tname = isInTable ? tinfo.getTable().name() : Table.ALL;

    Column column = columns.get(tname);
    Index index = indexes.get(tname);
    PartitionKey partitionKey = partitionKeys.get(tname);
    ClusteringKey clusteringKey = clusteringKeys.get(tname);
    TypeKey typeKey = typeKeys.get(tname);

    if (column == null) { // fallback to special Table.ALL name
        column = columns.get(Table.ALL);
    }
    this.column = column;
    if (index == null) { // fallback to special Table.ALL name
        index = indexes.get(Table.ALL);
    }
    this.index = index;
    if (partitionKey == null) { // fallback to special Table.ALL name
        partitionKey = partitionKeys.get(Table.ALL);
    }
    this.partitionKey = partitionKey;
    if (clusteringKey == null) { // fallback to special Table.ALL name
        clusteringKey = clusteringKeys.get(Table.ALL);
    }
    this.clusteringKey = clusteringKey;
    if (typeKey == null) { // fallback to special Table.ALL name
        typeKey = typeKeys.get(Table.ALL);
    }
    this.typeKey = typeKey;
    // validate some UDT stuff
    if (!isInTable) {
        org.apache.commons.lang3.Validate.isTrue(!isIndex(), "field cannot be annotated with @Index: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!isPartitionKey(),
                "field cannot be annotated with @PartitionKey: %s.%s", declaringClass.getName(),
                field.getName());
        org.apache.commons.lang3.Validate.isTrue(!isClusteringKey(),
                "field cannot be annotated with @ClusteringKey: %s.%s", declaringClass.getName(),
                field.getName());
        org.apache.commons.lang3.Validate.isTrue(!isTypeKey(), "field cannot be annotated with @TypeKey: %s.%s",
                declaringClass.getName(), field.getName());
    }
    if (isColumn()) {
        this.definition = DataTypeImpl.inferDataTypeFrom(field);
        this.decoder = definition.getDecoder(field, isMandatory() || isPartitionKey() || isClusteringKey());
        if (isInTable && ((clusteringKey != null) || (partitionKey != null))
                && (definition.getType() == DataType.SET)) {
            final Type type = field.getGenericType();

            if (type instanceof ParameterizedType) {
                final ParameterizedType ptype = (ParameterizedType) type;

                this.multiKeyType = ReflectionUtils.getRawClass(ptype.getActualTypeArguments()[0]); // sets will always have 1 argument
            } else {
                throw new IllegalArgumentException(
                        "unable to determine the element type of multi-field in table '" + tname + "': "
                                + declaringClass.getName() + "." + field.getName());
            }
        } else {
            this.multiKeyType = null;
        }
    } else {
        this.definition = null;
        this.decoder = null;
        this.multiKeyType = null;
    }
    this.getter = findGetterMethod(declaringClass);
    this.setter = findSetterMethod(declaringClass);
    this.finalValue = findFinalValue();
    // validate some stuff
    if (isInTable) {
        org.apache.commons.lang3.Validate.isTrue(!(isIndex() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @Index: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isPartitionKey() && isClusteringKey()),
                "field in table '%s' must not be annotated with @ClusteringKey if it is annotated with @PartitionKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isPartitionKey() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @PartitionKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isClusteringKey() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @ClusteringKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isTypeKey() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @TypeKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isTypeKey() && !String.class.equals(getType())),
                "field in table '%s' must be a String if it is annotated with @TypeKey: %s.%s", tname,
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isTypeKey() && isFinal()),
                "field in table '%s' must not be final if it is annotated with @TypeKey: %s.%s", tname,
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(
                !(isTypeKey() && !(cinfo instanceof RootClassInfoImpl)
                        && !(cinfo instanceof TypeClassInfoImpl)),
                "field in table '%s' must not be annotated with @TypeKey if class is annotated with @Entity: %s.%s",
                tname, declaringClass.getName(), field.getName());
        if (isColumn() && definition.isCollection()) {
            org.apache.commons.lang3.Validate.isTrue(
                    !((isClusteringKey() || isPartitionKey()) && (multiKeyType == null)),
                    "field in table '%s' cannot be '%s' if it is annotated with @ClusteringKey or @PartitionKey: %s.%s",
                    tname, definition, declaringClass.getName(), field.getName());
        }
    }
}

From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java

private int countFieldsInClass(Class<?> clazz) {
    int fieldCount = 0;
    for (Field field : clazz.getFields()) { // get all fields
        if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) {
            fieldCount++;/*from   ww  w. ja  v a 2s  .  c o  m*/
        }
    }
    return fieldCount;
}

From source file:fr.certu.chouette.command.Command.java

/**
 * @param object/*from w ww.  ja va2  s. c  o m*/
 * @throws Exception
 */
private void printFields(Object object, String indent) throws Exception {
    try {
        Class<?> c = object.getClass();
        Field[] fields = c.getSuperclass().getDeclaredFields();
        for (Field field : fields) {
            int m = field.getModifiers();
            if (Modifier.isPrivate(m) && !Modifier.isStatic(m)) {
                printField(c, field, indent);
            }

        }

        fields = c.getDeclaredFields();
        for (Field field : fields) {
            int m = field.getModifiers();
            if (Modifier.isPrivate(m) && !Modifier.isStatic(m)) {
                printField(c, field, indent);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:fr.certu.chouette.command.Command.java

/**
 * @param itemType/* w  ww. j  a  v a 2  s . co  m*/
 * @param indent
 * @throws Exception
 */
private void printFieldDetails(Class<?> itemType, String indent) throws Exception {
    String itemName = itemType.getName();
    if (itemName.startsWith("fr.certu.chouette.model.neptune.type.")) {
        if (itemName.endsWith("Enum")) {
            Field[] fields = itemType.getDeclaredFields();
            System.out.print(indent + "     ");

            String text = "";
            for (Field field : fields) {
                int m = field.getModifiers();
                if (Modifier.isPublic(m) && Modifier.isStatic(m) && Modifier.isFinal(m)) {
                    Object instance = field.get(null);
                    String name = instance.toString();
                    if (text.length() + name.length() > 79) {
                        System.out.print(text + "\n" + indent + "     ");
                        text = "";
                    }
                    text += name + " ";
                }
            }
            System.out.println(text);
        } else {
            Object instance = itemType.newInstance();
            printFields(instance, indent + "     ");
        }
    } else if (itemName.startsWith("fr.certu.chouette.model.neptune.")) {
        Object instance = itemType.newInstance();
        if (instance instanceof NeptuneIdentifiedObject) {
            String simpleName = itemType.getSimpleName();
            if (simpleName.equals("AreaCentroid")) {
                printFields(instance, indent + "     ");
            }
        } else {
            printFields(instance, indent + "     ");
        }

    }
}

From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java

/**
 * Checks if the given field is a valid pojo field:
 * - it is public/*  w  w w.j a  v a 2 s .co  m*/
 * OR
 *  - there are getter and setter methods for the field.
 *  
 * @param f field to check
 * @param clazz class of field
 * @param typeHierarchy type hierarchy for materializing generic types
 */
private boolean isValidPojoField(Field f, Class<?> clazz, ArrayList<Type> typeHierarchy) {
    if (Modifier.isPublic(f.getModifiers())) {
        return true;
    } else {
        boolean hasGetter = false, hasSetter = false;
        final String fieldNameLow = f.getName().toLowerCase().replaceAll("_", "");

        Type fieldType = f.getGenericType();
        Class<?> fieldTypeWrapper = ClassUtils.primitiveToWrapper(f.getType());

        TypeVariable<?> fieldTypeGeneric = null;
        if (fieldType instanceof TypeVariable) {
            fieldTypeGeneric = (TypeVariable<?>) fieldType;
            fieldType = materializeTypeVariable(typeHierarchy, (TypeVariable<?>) fieldType);
        }
        for (Method m : clazz.getMethods()) {
            final String methodNameLow = m.getName().endsWith("_$eq")
                    ? m.getName().toLowerCase().replaceAll("_", "").replaceFirst("\\$eq$", "_\\$eq")
                    : m.getName().toLowerCase().replaceAll("_", "");

            // check for getter
            if ( // The name should be "get<FieldName>" or "<fieldName>" (for scala) or "is<fieldName>" for boolean fields.
            (methodNameLow.equals("get" + fieldNameLow) || methodNameLow.equals("is" + fieldNameLow)
                    || methodNameLow.equals(fieldNameLow)) &&
            // no arguments for the getter
                    m.getParameterTypes().length == 0 &&
                    // return type is same as field type (or the generic variant of it)
                    (m.getGenericReturnType().equals(fieldType)
                            || (fieldTypeWrapper != null && m.getReturnType().equals(fieldTypeWrapper))
                            || (fieldTypeGeneric != null
                                    && m.getGenericReturnType().equals(fieldTypeGeneric)))) {
                if (hasGetter) {
                    throw new IllegalStateException("Detected more than one getter");
                }
                hasGetter = true;
            }
            // check for setters (<FieldName>_$eq for scala)
            if ((methodNameLow.equals("set" + fieldNameLow) || methodNameLow.equals(fieldNameLow + "_$eq"))
                    && m.getParameterTypes().length == 1 && // one parameter of the field's type
                    (m.getGenericParameterTypes()[0].equals(fieldType)
                            || (fieldTypeWrapper != null && m.getParameterTypes()[0].equals(fieldTypeWrapper))
                            || (fieldTypeGeneric != null
                                    && m.getGenericParameterTypes()[0].equals(fieldTypeGeneric)))
                    &&
                    // return type is void.
                    m.getReturnType().equals(Void.TYPE)) {
                if (hasSetter) {
                    throw new IllegalStateException("Detected more than one setter");
                }
                hasSetter = true;
            }
        }
        if (hasGetter && hasSetter) {
            return true;
        } else {
            if (!hasGetter) {
                LOG.debug(clazz + " does not contain a getter for field " + f.getName());
            }
            if (!hasSetter) {
                LOG.debug(clazz + " does not contain a setter for field " + f.getName());
            }
            return false;
        }
    }
}