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:org.openmrs.util.OpenmrsClassLoader.java

/**
 * Used by {@link #clearReferences()} upon application close. <br>
 * <br>/*from   ww  w.j  a va2  s .  co  m*/
 * Borrowed from Tomcat's WebappClassLoader.
 *
 * @param instance the object whose fields need to be nulled out
 */
protected static void nullInstance(Object instance) {
    if (instance == null) {
        return;
    }
    Field[] fields = instance.getClass().getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        int mods = field.getModifiers();
        if (field.getType().isPrimitive() || (field.getName().indexOf("$") != -1)) {
            continue;
        }
        try {
            field.setAccessible(true);
            if (Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
                // Doing something recursively is too risky
                continue;
            } else {
                Object value = field.get(instance);
                if (null != value) {
                    Class<?> valueClass = value.getClass();
                    if (!loadedByThisOrChild(valueClass)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Not setting field " + field.getName() + " to null in object of class "
                                    + instance.getClass().getName()
                                    + " because the referenced object was of type " + valueClass.getName()
                                    + " which was not loaded by this WebappClassLoader.");
                        }
                    } else {
                        field.set(instance, null);
                        if (log.isDebugEnabled()) {
                            log.debug("Set field " + field.getName() + " to null in class "
                                    + instance.getClass().getName());
                        }
                    }
                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Could not set field " + field.getName() + " to null in object instance of class "
                        + instance.getClass().getName(), e);
            }
        }
    }
}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedProxyClassGenerator.java

private void writePropertyMethods(ClassVisitor visitor, Type generatedType, ModelStructSchema<?> managedSchema,
        ModelStructSchema<?> delegateSchema) {
    Collection<String> delegatePropertyNames;
    if (delegateSchema != null) {
        ImmutableSet.Builder<String> builder = ImmutableSet.builder();
        for (ModelProperty<?> delegateProperty : delegateSchema.getProperties()) {
            builder.add(delegateProperty.getName());
        }//  ww w.ja v a 2  s . c o  m
        delegatePropertyNames = builder.build();
    } else {
        delegatePropertyNames = Collections.emptySet();
    }
    Class<?> managedTypeClass = managedSchema.getType().getConcreteClass();
    for (ModelProperty<?> property : managedSchema.getProperties()) {
        String propertyName = property.getName();
        // Delegated properties are handled in writeDelegateMethods()
        if (delegatePropertyNames.contains(propertyName)) {
            continue;
        }
        switch (property.getStateManagementType()) {
        case MANAGED:
            writeGetters(visitor, generatedType, property);
            writeSetter(visitor, generatedType, property);
            break;

        case UNMANAGED:
            String getterName = getGetterName(propertyName);
            Method getterMethod;
            try {
                getterMethod = managedTypeClass.getMethod(getterName);
            } catch (NoSuchMethodException e) {
                throw new IllegalStateException(String.format("Cannot find getter '%s' on type %s", getterName,
                        managedTypeClass.getName()), e);
            }
            if (!Modifier.isFinal(getterMethod.getModifiers()) && !propertyName.equals("metaClass")) {
                writeNonAbstractMethodWrapper(visitor, generatedType, managedTypeClass, getterMethod);
            }
            break;
        }
    }
}

From source file:org.latticesoft.util.common.StringUtil.java

/**
 * Print the properties of an object into a xml string.
 * This is useful in the object's toString method.
 * @param o the object to be converted/*  ww  w .j  a  v a2  s .c  o  m*/
 * @param mode one of the above mode
 * @param displayAll display all attributes including those which are null.
 * @return the string-fied xml form of the object
 */
public static String formatObjectToXmlString(Object o, int mode, boolean displayAll) {
    if (o == null)
        return "<NullClass/>";

    StringBuffer sb = new StringBuffer();
    String s = o.getClass().getName();
    String p = o.getClass().getPackage().getName();
    String className = s.substring(p.length() + 1, s.length());

    if (mode == StringUtil.MODE_END_TAG) {
        sb.append("</");
        sb.append(className);
        sb.append(">");
        return sb.toString();
    }

    sb.append("<");
    sb.append(className);

    // list of attributes
    Field f[] = o.getClass().getDeclaredFields();
    WrapDynaBean dyn = null;
    try {
        dyn = new WrapDynaBean(o);
    } catch (Exception e) {
    }

    for (int i = 0; i < f.length; i++) {
        String name = f[i].getName();
        int modifier = f[i].getModifiers();
        if (Modifier.isFinal(modifier) || Modifier.isAbstract(modifier) || Modifier.isInterface(modifier)
                || Modifier.isStatic(modifier)) {
            continue;
        }

        Object value = null;
        try {
            value = dyn.get(name);
        } catch (Exception e) {
            //if (log.isErrorEnabled()) { log.error(e); }
        }
        if (name != null) {
            if ((value != null && !displayAll) || (displayAll)) {
                sb.append(" ");
                sb.append(name);
                sb.append("=\"");
                sb.append(value);
                sb.append("\"");
            }
        }
    }
    switch (mode) {
    default:
    case StringUtil.MODE_FULL_STANDARD:
        sb.append("/>");
        break;
    case StringUtil.MODE_FULL_LONG:
        sb.append("></");
        sb.append(className);
        sb.append(">");
        break;
    case StringUtil.MODE_START_TAG:
        sb.append(">");
        break;
    }
    return sb.toString();
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Generate the bytecode for a bean proxy for the given type.
 */// ww  w  . j av  a  2 s .  c o m
protected BCClass generateProxyBeanBytecode(Class type, boolean runtime) {
    if (Modifier.isFinal(type.getModifiers()))
        return null;
    if (ImplHelper.isManagedType(null, type))
        return null;

    // we can only generate a valid proxy if there is a copy constructor
    // or a default constructor
    Constructor cons = findCopyConstructor(type);
    if (cons == null) {
        Constructor[] cs = type.getConstructors();
        for (int i = 0; cons == null && i < cs.length; i++)
            if (cs[i].getParameterTypes().length == 0)
                cons = cs[i];
        if (cons == null)
            return null;
    }

    Project project = new Project();
    BCClass bc = AccessController
            .doPrivileged(J2DoPrivHelper.loadProjectClassAction(project, getProxyClassName(type, runtime)));
    bc.setSuperclass(type);
    bc.declareInterface(ProxyBean.class);

    delegateConstructors(bc, type);
    addProxyMethods(bc, true);
    addProxyBeanMethods(bc, type, cons);
    if (!proxySetters(bc, type))
        return null;
    addWriteReplaceMethod(bc, runtime);
    return bc;
}

From source file:adalid.core.AbstractArtifact.java

private boolean isNotRestricted(Field field) {
    int modifiers = field.getModifiers();
    return !(Modifier.isPrivate(modifiers) || Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers));
}

From source file:org.soyatec.windowsazure.table.internal.CloudTableRest.java

/**
 * Deserial the xml to object accord to the give model class.
 *
 * @param partitionKey// w ww . jav a2  s .com
 * @param rowKey
 * @param eTag
 * @param timestamp
 * @param values
 * @return Instance of the given model class.
 */
private ITableServiceEntity createObjectByModelClass(String partitionKey, String rowKey, String eTag,
        String timestamp, List<ICloudTableColumn> values) {
    ITableServiceEntity newInstance = instanceModel(partitionKey, rowKey, eTag, timestamp, values);
    if (newInstance == null) {
        return null;
    }
    // Copy Field
    if (values != null && !values.isEmpty()) {
        for (ICloudTableColumn column : values) {
            Field field = null;
            try {
                field = newInstance.getClass().getDeclaredField(column.getName());
            } catch (NoSuchFieldException e) {
                continue;
            }

            if (field == null) {
                continue;
            }
            int modifier = field.getModifiers();
            if (Modifier.isPrivate(modifier) && Modifier.isFinal(modifier) && Modifier.isStatic(modifier)) {
                if (getModelClass() != null) {
                    Logger.debug(MessageFormat.format(
                            "{0} class {1} is a static final field. Can not set data to it.",
                            getModelClass().getClass(), field.getName()));
                }
                continue;
            }

            boolean accessible = field.isAccessible();
            if (!accessible) {
                field.setAccessible(true);
            }
            ETableColumnType type = column.getType();
            String value = column.getValue();
            if (value == null) {
                continue;
            } else {
                try {
                    if (type == null) {
                        setStringOrObjectField(newInstance, column, field, value);
                    } else if (type.equals(ETableColumnType.TYPE_BINARY)) {
                        field.set(newInstance, Base64.decode(value));
                    } else if (type.equals(ETableColumnType.TYPE_BOOL)) {
                        field.setBoolean(newInstance, Boolean.parseBoolean(value));
                    } else if (type.equals(ETableColumnType.TYPE_DATE_TIME)) {
                        field.set(newInstance, Utilities.tryGetDateTimeFromTableEntry(value));
                    } else if (type.equals(ETableColumnType.TYPE_DOUBLE)) {
                        field.setDouble(newInstance, Double.parseDouble(value));
                    } else if (type.equals(ETableColumnType.TYPE_GUID)) {
                        Guid guid = new Guid();
                        try {
                            Field valueField = guid.getClass().getDeclaredField("value");
                            boolean accessiable = valueField.isAccessible();
                            if (!accessible) {
                                valueField.setAccessible(true);
                            }
                            valueField.set(guid, value);
                            valueField.setAccessible(accessiable);
                            field.set(newInstance, guid);
                        } catch (NoSuchFieldException e) {
                            Logger.error(e.getMessage(), e);
                        }
                    } else if (type.equals(ETableColumnType.TYPE_INT)) {
                        try {
                            field.setInt(newInstance, Integer.parseInt(value));
                        } catch (Exception e) {
                            field.setByte(newInstance, Byte.parseByte(value));
                        }
                    } else if (type.equals(ETableColumnType.TYPE_LONG)) {
                        field.setLong(newInstance, Long.parseLong(value));
                    } else if (type.equals(ETableColumnType.TYPE_STRING)) {
                        setStringOrObjectField(newInstance, column, field, value);
                    }
                } catch (Exception e) {
                    Logger.error(
                            MessageFormat.format("{0} class filed {1} set failed.", getModelClass(), value), e);
                }
            }
            // revert aaccessible
            field.setAccessible(accessible);
        }
    }
    return newInstance;
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Checks if is final./*from w w  w  .ja v a2s . c  o  m*/
 * 
 * @param field
 *          the field
 * @return true, if is final
 */
public static boolean isFinal(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isFinal(modifiers);
}

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

/**
 * Finds all final fields in this class and all super classes up to and
 * excluding the first class that is not annotated with the corresponding
 * entity annotation./*ww  w.jav  a  2 s  .  c  o m*/
 *
 * @author paouelle
 *
 * @return a non-<code>null</code> map of all final fields and their default
 *         values
 */
private Map<Field, Object> findFinalFields() {
    final Map<Field, Object> ffields = new HashMap<>(8);
    MutableObject<Object> obj = null; // lazy evaluated

    // go up the hierarchy until we hit the class for which we have a default
    // serialization constructor as that class will have its final fields
    // properly initialized by the ctor whereas all others will have their final
    // fields initialized with 0, false, null, ...
    for (Class<? super T> clazz = this.clazz; clazz != constructor.getDeclaringClass(); clazz = clazz
            .getSuperclass()) {
        for (final Field field : clazz.getDeclaredFields()) {
            final int mods = field.getModifiers();

            if (Modifier.isFinal(mods) && !Modifier.isStatic(mods)) {
                field.setAccessible(true); // so we can access its value directly
                if (obj == null) {
                    // instantiates a dummy version and access its value
                    try {
                        // find default ctor even if private
                        final Constructor<T> ctor = this.clazz.getDeclaredConstructor();

                        ctor.setAccessible(true); // in case it was private
                        final T t = ctor.newInstance();

                        obj = new MutableObject<>(t);
                    } catch (NoSuchMethodException | IllegalAccessException | InstantiationException e) {
                        throw new IllegalArgumentException(
                                "unable to instantiate object: " + this.clazz.getName(), e);
                    } catch (InvocationTargetException e) {
                        final Throwable t = e.getTargetException();

                        if (t instanceof Error) {
                            throw (Error) t;
                        } else if (t instanceof RuntimeException) {
                            throw (RuntimeException) t;
                        } else { // we don't expect any of those
                            throw new IllegalArgumentException(
                                    "unable to instantiate object: " + this.clazz.getName(), t);
                        }
                    }
                }
                try {
                    ffields.put(field, field.get(obj.getValue()));
                } catch (IllegalAccessException e) {
                    throw new IllegalArgumentException("unable to access final value for field: "
                            + field.getDeclaringClass().getName() + "." + field.getName(), e);
                }
            }
        }
    }
    return ffields;
}

From source file:adalid.core.XS1.java

static Field getField(boolean log, String role, String name, Class<?> type, Class<?> top,
        Class<?>... validTypes) {
    String string;//from w ww  .j a  v  a 2s. c o m
    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:org.evosuite.setup.TestClusterGenerator.java

/**
 * Get the set of fields defined in this class and its superclasses
 * /*from   w w  w  .  j  a v  a  2s .  c o m*/
 * @param clazz
 * @return
 */
public static Set<Field> getAccessibleFields(Class<?> clazz) {
    Set<Field> fields = new LinkedHashSet<Field>();
    try {
        for (Field f : clazz.getFields()) {
            if (canUse(f) && !Modifier.isFinal(f.getModifiers())) {
                fields.add(f);
            }
        }
    } catch (Throwable t) {
        logger.info("Error while accessing fields of class {} - check allowed permissions: {}", clazz.getName(),
                t);
    }
    return fields;
}