Example usage for java.lang.reflect Modifier isFinal

List of usage examples for java.lang.reflect Modifier isFinal

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isFinal.

Prototype

public static boolean isFinal(int mod) 

Source Link

Document

Return true if the integer argument includes the final modifier, false otherwise.

Usage

From source file:com.mycila.plugin.Cglib2AopProxy.java

/**
 * Checks for final methods on the <code>Class</code> and writes warnings to the log
 * for each one found.//from   w  w w . j av  a  2 s .  c  om
 */
private void doValidateClass(Class proxySuperClass) {
    Method[] methods = proxySuperClass.getMethods();
    for (Method method : methods) {
        if (!Object.class.equals(method.getDeclaringClass()) && Modifier.isFinal(method.getModifiers())) {
            logger.warn("Unable to proxy method [" + method + "] because it is final: "
                    + "All calls to this method via a proxy will be routed directly to the proxy.");
        }
    }
}

From source file:cern.c2mon.shared.common.datatag.address.impl.HardwareAddressImpl.java

/**
 * Returns an XML representation of the HardwareAddress object.
 *
 * @throws RuntimeException if Illegal access to fields
 *//*from  w  w w  .  jav a  2  s.c o  m*/
public final synchronized String toConfigXML() {
    Class handlerClass = this.getClass();
    Field[] fields = handlerClass.getDeclaredFields();

    StringBuilder str = new StringBuilder();

    str.append("        <HardwareAddress class=\"");
    str.append(getClass().getName());
    str.append("\">\n");

    for (int i = 0; i < fields.length; i++) {
        if (Modifier.isProtected(fields[i].getModifiers()) && !Modifier.isFinal(fields[i].getModifiers())) {
            try {
                if (fields[i].get(this) != null) {
                    str.append("          <");
                    String fieldXMLName = encodeFieldName(fields[i].getName());

                    str.append(fieldXMLName);
                    str.append(">");
                    try {
                        str.append(fields[i].get(this));
                    } catch (IllegalAccessException iae) {
                        iae.printStackTrace();
                    }
                    str.append("</");
                    str.append(fieldXMLName);
                    str.append(">\n");
                }
            } catch (IllegalAccessException iae) {
                iae.printStackTrace();
                throw new RuntimeException("Exception caught while converting HardwareAddress to XML.", iae);
            }
        }
    }

    str.append("        </HardwareAddress>\n");
    return str.toString();
}

From source file:com.microsoft.tfs.client.common.ui.framework.layout.GridDataBuilder.java

/**
 * Performs a copy operation on the specified {@link GridData}, returning a
 * new {@link GridData} instance that has all fields set to the same value
 * as the input {@link GridData}./*from   ww  w .j a  v a  2  s  .  c om*/
 *
 * @param in
 *        an input {@link GridData} (must not be <code>null</code>)
 * @return a copy of the input
 */
private static GridData copy(final GridData in) {
    final GridData out = new GridData();

    /*
     * The copy is done reflectively instead of directly. The GridData class
     * has added lots of fields in different versions of Eclipse since 3.0 -
     * this is the easiest way to get compatibility with all those versions.
     */

    /*
     * PERF: consider caching the final Field[] array.
     */

    final Field[] fields = GridData.class.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        if (Modifier.isStatic(fields[i].getModifiers()) || Modifier.isFinal(fields[i].getModifiers())) {
            /*
             * skip static and final fields
             */
            continue;
        }

        fields[i].setAccessible(true);
        try {
            final Object valueToCopy = fields[i].get(in);
            fields[i].set(out, valueToCopy);
        } catch (final IllegalArgumentException e) {
            final String messageFormat = "field [{0}]: {1}"; //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, fields[i].getName(), e.getMessage());
            throw new RuntimeException(message, e);
        } catch (final IllegalAccessException e) {
            final String messageFormat = "field [{0}]: {1}"; //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, fields[i].getName(), e.getMessage());
            throw new RuntimeException(message, e);
        }
    }

    return out;
}

From source file:com.unovo.frame.utils.SharedPreferencesHelper.java

private static boolean isContSupport(Field field) {
    return (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())
            || Modifier.isAbstract(field.getModifiers()));
}

From source file:org.springframework.aop.framework.CglibAopProxy.java

/**
 * Checks for final methods on the given {@code Class}, as well as package-visible
 * methods across ClassLoaders, and writes warnings to the log for each one found.
 */// w ww .  ja  v  a  2  s.  c  o  m
private void doValidateClass(Class<?> proxySuperClass, @Nullable ClassLoader proxyClassLoader,
        Set<Class<?>> ifcs) {
    if (proxySuperClass != Object.class) {
        Method[] methods = proxySuperClass.getDeclaredMethods();
        for (Method method : methods) {
            int mod = method.getModifiers();
            if (!Modifier.isStatic(mod) && !Modifier.isPrivate(mod)) {
                if (Modifier.isFinal(mod)) {
                    if (implementsInterface(method, ifcs)) {
                        logger.warn("Unable to proxy interface-implementing method [" + method + "] because "
                                + "it is marked as final: Consider using interface-based JDK proxies instead!");
                    }
                    logger.info("Final method [" + method + "] cannot get proxied via CGLIB: "
                            + "Calls to this method will NOT be routed to the target instance and "
                            + "might lead to NPEs against uninitialized fields in the proxy instance.");
                } else if (!Modifier.isPublic(mod) && !Modifier.isProtected(mod) && proxyClassLoader != null
                        && proxySuperClass.getClassLoader() != proxyClassLoader) {
                    logger.info("Method [" + method + "] is package-visible across different ClassLoaders "
                            + "and cannot get proxied via CGLIB: Declare this method as public or protected "
                            + "if you need to support invocations through the proxy.");
                }
            }
        }
        doValidateClass(proxySuperClass.getSuperclass(), proxyClassLoader, ifcs);
    }
}

From source file:com.jwebmp.core.htmlbuilder.javascript.JavaScriptPart.java

/**
 * Renders the fields (getDeclaredFields()) as a map of html attributes
 *
 * @return//from  w  w  w . j  a va 2s .c  om
 */
public Map<String, String> toAttributes() {
    Map<String, String> map = new LinkedHashMap<>();

    Field[] fields = getClass().getDeclaredFields();
    for (Field field : fields) {
        if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) {
            continue;
        }
        field.setAccessible(true);
        try {
            Object result = field.get(this);
            if (result != null) {
                if (JavaScriptPart.class.isAssignableFrom(result.getClass())) {
                    map.put(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, field.getName()),
                            ((JavaScriptPart) result).toString(true));
                } else {
                    map.put(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, field.getName()),
                            result.toString());
                }
            }
        } catch (Exception e) {
            JavaScriptPart.log.log(Level.WARNING, "Cant format as attributes", e);
        }
    }
    return map;
}

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];//from   ww  w . jav a  2 s. c o m
        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();
        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:org.eclipse.skalli.services.persistence.EntityManagerServiceBase.java

static Set<String> getPublicStaticFinalFieldValues(Class<?> clazz) {
    Set<String> properties = new HashSet<String>();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        if (field.getType().isAssignableFrom(String.class)) {
            int mod = field.getModifiers();
            if (Modifier.isPublic(mod) && Modifier.isStatic(mod) && Modifier.isFinal(mod)) {
                try {
                    String propertyValue = field.get(null).toString();
                    if (StringUtils.isNotBlank(propertyValue)) {
                        properties.add(propertyValue);
                    }//from  w  w  w  . j  a v  a2 s .c  o m
                } catch (Exception e) {
                    LOG.error("Failed to read public static final fields of class " + clazz, e);
                }
            }
        }
    }
    return properties;
}

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  w w w .  j  av  a  2  s  .c  om
 *
 * @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());
        }
    }
}