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.nuxeo.client.api.objects.Document.java

/**
 * This constructor is providing a way to create 'adapters' of a document. See
 * org.nuxeo.client.test.objects.DataSet in nuxeo-java-client-test.
 *
 * @since 1.0/*from   w  w  w  . j  av a 2  s . c o m*/
 * @param document the document to copy from the sub class.
 */
public Document(Document document) {
    super(ConstantsV1.ENTITY_TYPE_DOCUMENT);
    type = ConstantsV1.DEFAULT_DOC_TYPE;
    for (Field field : document.getClass().getDeclaredFields()) {
        if (!Modifier.isFinal(field.getModifiers())) {
            try {
                Class<?> superclass = this.getClass().getSuperclass();
                if (superclass.equals(NuxeoEntity.class)) {
                    throw new NuxeoClientException(
                            "You should never use this constructor unless you're using a subclass of Document");
                }
                superclass.getDeclaredField(field.getName()).set(this, field.get(document));
            } catch (NoSuchFieldException | IllegalAccessException reason) {
                throw new NuxeoClientException(reason);
            }
        }
    }
}

From source file:objenome.util.bytecode.SgUtils.java

/**
 * Checks if the modifiers are valid for a class. If any of the modifiers is
 * not valid an <code>IllegalArgumentException</code> is thrown.
 * //from  w w  w  .  j a v a 2s.c  o  m
 * @param modifiers
 *            Modifiers.
 * @param isInterface
 *            Are the modifiers from an interface?
 * @param isInnerClass
 *            Is it an inner class?
 */
public static void checkClassModifiers(int modifiers, boolean isInterface, boolean isInnerClass) {

    // Basic checks
    int type;
    if (isInterface) {
        type = isInnerClass ? INNER_INTERFACE : OUTER_INTERFACE;
    } else {
        type = isInnerClass ? INNER_CLASS : OUTER_CLASS;
    }
    checkModifiers(type, modifiers);

    // Abstract and final check
    if (Modifier.isAbstract(modifiers) && Modifier.isFinal(modifiers)) {
        throw new IllegalArgumentException(
                CLASS_ABSTRACT_AND_FINAL_ERROR + " [" + Modifier.toString(modifiers) + ']');
    }

}

From source file:tech.sirwellington.alchemy.generator.ObjectGenerators.java

private static boolean isFinal(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isFinal(modifiers);
}

From source file:org.j2free.admin.ReflectionMarshaller.java

private ReflectionMarshaller(Class klass) throws Exception {

    instructions = new HashMap<Field, Converter>();

    LinkedList<Field> fieldsToMarshall = new LinkedList<Field>();

    // Only marshallOut entities
    if (!klass.isAnnotationPresent(Entity.class))
        throw new Exception("Provided class is not an @Entity");

    // Add the declared fields
    fieldsToMarshall.addAll(Arrays.asList(klass.getDeclaredFields()));

    /* Inheritence support
     * Continue up the inheritance ladder until:
     *   - There are no more super classes (zuper == null), or
     *   - The super class is not an @Entity
     *///from ww  w.  j a va 2 s.  co  m
    Class zuper = klass;
    while ((zuper = zuper.getSuperclass()) != null) {

        // get out if we find a super class that isn't an @Entity
        if (!klass.isAnnotationPresent(Entity.class))
            break;

        // Add the declared fields
        // @todo, improve the inheritance support, the current way will overwrite
        // overridden fields in subclasses with the super class's field
        fieldsToMarshall.addAll(Arrays.asList(zuper.getDeclaredFields()));
    }

    /* By now, fieldsToMarshall should contain all the fields
     * so it's time to figure out how to access them.
     */
    Method getter, setter;
    Converter converter;
    for (Field field : fieldsToMarshall) {

        int mod = field.getModifiers();
        if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
            log.debug("Skipping final or static field " + field.getName());
            continue;
        }

        getter = setter = null;

        // if direct access doesn't work, look for JavaBean
        // getters and setters
        String fieldName = field.getName();
        Class fieldType = field.getType();

        try {
            getter = getGetter(field);
        } catch (NoSuchMethodException nsme) {
            log.debug("Failed to find getter for " + fieldName);
        }

        try {
            setter = getSetter(field);
        } catch (NoSuchMethodException nsme) {
            log.debug("Failed to find setter for " + fieldName);
        }

        if (getter == null && setter == null) {
            // Shit, we didn't figure out how to access it
            log.debug("Could not access field: " + field.getName());
        } else {
            converter = new Converter(getter, setter);

            if (field.isAnnotationPresent(Id.class)) {
                log.debug("Found entityIdFied for " + klass.getName() + ": " + field.getName());
                entityIdField = field;
                embeddedId = false;
            }

            if (field.isAnnotationPresent(EmbeddedId.class)) {
                log.debug("Found embedded entityIdFied for " + klass.getName() + ": " + field.getName());
                entityIdField = field;
                embeddedId = true;
            }

            if (field.isAnnotationPresent(GeneratedValue.class) || setter == null) {
                converter.setReadOnly(true);
            }

            if (field.getType().isAnnotationPresent(Entity.class)) {
                converter.setEntity(fieldType);
            }

            Class superClass = field.getType();
            if (superClass != null) {
                do {
                    if (superClass == Collection.class) {
                        try {
                            Type type = field.getGenericType();
                            String typeString = type.toString();

                            while (typeString.matches("[^<]+?<[^>]+?>"))
                                typeString = typeString.substring(typeString.indexOf("<") + 1,
                                        typeString.indexOf(">"));

                            Class collectionType = Class.forName(typeString);
                            converter.setCollection(collectionType);

                            if (collectionType.getAnnotation(Entity.class) != null)
                                converter.setEntity(collectionType);

                            log.debug(field.getName() + " is entity = " + converter.isEntity());
                            log.debug(field.getName() + " collectionType = "
                                    + converter.getType().getSimpleName());

                        } catch (Exception e) {
                            log.debug("error getting collection type", e);
                        } finally {
                            break;
                        }
                    }
                    superClass = superClass.getSuperclass();
                } while (superClass != null);
            }

            instructions.put(field, converter);
        }
    }
}

From source file:org.eclipse.e4.emf.internal.xpath.helper.ValueUtils.java

public static int getCollectionHint(Class<?> clazz) {
    if (clazz.isArray()) {
        return 1;
    }//from ww w  .  java2  s  .c  o  m

    if (Collection.class.isAssignableFrom(clazz)) {
        return 1;
    }

    if (clazz.isPrimitive()) {
        return -1;
    }

    if (clazz.isInterface()) {
        return 0;
    }

    if (Modifier.isFinal(clazz.getModifiers())) {
        return -1;
    }

    return 0;
}

From source file:com.zuoxiaolong.niubi.job.persistent.BaseDaoImpl.java

private <T> List<Object> generateValueListAndSetSql(Class<T> clazz, T entity, StringBuffer sqlBuffer,
        boolean useLike) {
    List<Object> valueList = new ArrayList<>();
    if (entity != null) {
        Field[] fields = ReflectHelper.getAllFields(entity);
        for (int i = 0, index = 0; i < fields.length; i++) {
            Field field = fields[i];
            int modifiers = field.getModifiers();
            if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers) || Modifier.isFinal(modifiers)
                    || ObjectHelper.isTransientId(clazz, field)) {
                continue;
            }/* w ww .jav  a 2s  .c  o m*/
            Object value = ReflectHelper.getFieldValueWithGetterMethod(entity, entity.getClass(),
                    field.getName());
            if (ObjectHelper.isEmpty(value)) {
                continue;
            }
            if (field.getType() == String.class && useLike) {
                sqlBuffer.append("and " + field.getName() + " like ?" + index++ + " ");
                valueList.add("%" + value + "%");
            } else {
                sqlBuffer.append("and " + field.getName() + "=?" + index++ + " ");
                valueList.add(value);
            }
        }
    }
    return valueList;
}

From source file:org.apache.axis.utils.BeanUtils.java

public static BeanPropertyDescriptor[] processPropertyDescriptors(PropertyDescriptor[] rawPd, Class cls,
        TypeDesc typeDesc) {/*  w ww.  j  a va2s  .com*/

    // Create a copy of the rawPd called myPd
    BeanPropertyDescriptor[] myPd = new BeanPropertyDescriptor[rawPd.length];

    ArrayList pd = new ArrayList();

    try {
        for (int i = 0; i < rawPd.length; i++) {
            // Skip the special "any" field
            if (rawPd[i].getName().equals(Constants.ANYCONTENT))
                continue;
            pd.add(new BeanPropertyDescriptor(rawPd[i]));
        }

        // Now look for public fields
        Field fields[] = cls.getFields();
        if (fields != null && fields.length > 0) {
            // See if the field is in the list of properties
            // add it if not.
            for (int i = 0; i < fields.length; i++) {
                Field f = fields[i];
                // skip if field come from a java.* or javax.* package
                // WARNING: Is this going to make bad things happen for
                // users JavaBeans?  Do they WANT these fields serialzed?
                String clsName = f.getDeclaringClass().getName();
                if (clsName.startsWith("java.") || clsName.startsWith("javax.")) {
                    continue;
                }
                // skip field if it is final, transient, or static
                if (!(Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())
                        || Modifier.isTransient(f.getModifiers()))) {
                    String fName = f.getName();
                    boolean found = false;
                    for (int j = 0; j < rawPd.length && !found; j++) {
                        String pName = ((BeanPropertyDescriptor) pd.get(j)).getName();
                        if (pName.length() == fName.length()
                                && pName.substring(0, 1).equalsIgnoreCase(fName.substring(0, 1))) {

                            found = pName.length() == 1 || pName.substring(1).equals(fName.substring(1));
                        }
                    }

                    if (!found) {
                        pd.add(new FieldPropertyDescriptor(f.getName(), f));
                    }
                }
            }
        }

        // If typeDesc meta data exists, re-order according to the fields
        if (typeDesc != null && typeDesc.getFields(true) != null) {
            ArrayList ordered = new ArrayList();
            // Add the TypeDesc elements first
            FieldDesc[] fds = typeDesc.getFields(true);
            for (int i = 0; i < fds.length; i++) {
                FieldDesc field = fds[i];
                if (field.isElement()) {
                    boolean found = false;
                    for (int j = 0; j < pd.size() && !found; j++) {
                        if (field.getFieldName().equals(((BeanPropertyDescriptor) pd.get(j)).getName())) {
                            ordered.add(pd.remove(j));
                            found = true;
                        }
                    }
                }
            }
            // Add the remaining elements
            while (pd.size() > 0) {
                ordered.add(pd.remove(0));
            }
            // Use the ordered list
            pd = ordered;
        }

        myPd = new BeanPropertyDescriptor[pd.size()];
        for (int i = 0; i < pd.size(); i++) {
            myPd[i] = (BeanPropertyDescriptor) pd.get(i);
        }
    } catch (Exception e) {
        log.error(Messages.getMessage("badPropertyDesc00", cls.getName()), e);
        throw new InternalException(e);
    }

    return myPd;
}

From source file:com.googlecode.jsonschema2pojo.rules.ObjectRule.java

private boolean isFinal(JType superType) {
    try {//from w w w  .  jav a 2s .  c om
        Class<?> javaClass = Class.forName(superType.fullName());
        return Modifier.isFinal(javaClass.getModifiers());
    } catch (ClassNotFoundException e) {
        return false;
    }
}

From source file:org.hibernate.tuple.entity.PojoEntityTuplizer.java

/**
 * {@inheritDoc}/*ww w  .  j a v  a  2  s. c o m*/
 */
protected ProxyFactory buildProxyFactory(PersistentClass persistentClass, Getter idGetter, Setter idSetter) {
    // determine the id getter and setter methods from the proxy interface (if any)
    // determine all interfaces needed by the resulting proxy
    HashSet proxyInterfaces = new HashSet();
    proxyInterfaces.add(HibernateProxy.class);

    Class mappedClass = persistentClass.getMappedClass();
    Class proxyInterface = persistentClass.getProxyInterface();

    if (proxyInterface != null && !mappedClass.equals(proxyInterface)) {
        if (!proxyInterface.isInterface()) {
            throw new MappingException(
                    "proxy must be either an interface, or the class itself: " + getEntityName());
        }
        proxyInterfaces.add(proxyInterface);
    }

    if (mappedClass.isInterface()) {
        proxyInterfaces.add(mappedClass);
    }

    Iterator iter = persistentClass.getSubclassIterator();
    while (iter.hasNext()) {
        Subclass subclass = (Subclass) iter.next();
        Class subclassProxy = subclass.getProxyInterface();
        Class subclassClass = subclass.getMappedClass();
        if (subclassProxy != null && !subclassClass.equals(subclassProxy)) {
            if (!proxyInterface.isInterface()) {
                throw new MappingException(
                        "proxy must be either an interface, or the class itself: " + subclass.getEntityName());
            }
            proxyInterfaces.add(subclassProxy);
        }
    }

    Iterator properties = persistentClass.getPropertyIterator();
    Class clazz = persistentClass.getMappedClass();
    while (properties.hasNext()) {
        Property property = (Property) properties.next();
        Method method = property.getGetter(clazz).getMethod();
        if (method != null && Modifier.isFinal(method.getModifiers())) {
            log.error("Getters of lazy classes cannot be final: " + persistentClass.getEntityName() + "."
                    + property.getName());
        }
        method = property.getSetter(clazz).getMethod();
        if (method != null && Modifier.isFinal(method.getModifiers())) {
            log.error("Setters of lazy classes cannot be final: " + persistentClass.getEntityName() + "."
                    + property.getName());
        }
    }

    Method idGetterMethod = idGetter == null ? null : idGetter.getMethod();
    Method idSetterMethod = idSetter == null ? null : idSetter.getMethod();

    Method proxyGetIdentifierMethod = idGetterMethod == null || proxyInterface == null ? null
            : ReflectHelper.getMethod(proxyInterface, idGetterMethod);
    Method proxySetIdentifierMethod = idSetterMethod == null || proxyInterface == null ? null
            : ReflectHelper.getMethod(proxyInterface, idSetterMethod);

    ProxyFactory pf = buildProxyFactoryInternal(persistentClass, idGetter, idSetter);
    try {
        pf.postInstantiate(getEntityName(), mappedClass, proxyInterfaces, proxyGetIdentifierMethod,
                proxySetIdentifierMethod,
                persistentClass.hasEmbeddedIdentifier()
                        ? (AbstractComponentType) persistentClass.getIdentifier().getType()
                        : null);
    } catch (HibernateException he) {
        log.warn("could not create proxy factory for:" + getEntityName(), he);
        pf = null;
    }
    return pf;
}

From source file:net.servicefixture.util.ReflectionUtils.java

public static String getDefaultValue(Class type) {
    if (isEnumarationPatternClass(type)) {
        StringBuilder sb = new StringBuilder();
        Field[] fields = type.getFields();
        for (int i = 0; i < fields.length; i++) {
            if (type.equals(fields[i].getType()) && Modifier.isFinal(fields[i].getModifiers())
                    && Modifier.isPublic(fields[i].getModifiers())
                    && Modifier.isStatic(fields[i].getModifiers())) {
                try {
                    sb.append(fields[i].getName()).append(";");
                } catch (IllegalArgumentException e) {
                }//from  www.  ja  v  a 2 s . c om
            }
        }
        return sb.toString();
    } else if (type.isEnum()) {
        StringBuilder sb = new StringBuilder();
        try {
            Object[] array = (Object[]) type.getMethod("values").invoke(null);
            for (int i = 0; i < array.length; i++) {
                sb.append(array[i]).append(";");
            }
        } catch (Exception e) {
        }
        return sb.toString();

    } else if (Calendar.class.isAssignableFrom(type) || XMLGregorianCalendar.class.isAssignableFrom(type)) {
        return "${calendar.after(0)}";
    } else if (Date.class.isAssignableFrom(type)) {
        return "${date.after(0)}";
    } else if (Number.class.isAssignableFrom(type) || "long".equals(type.getName())
            || "int".equals(type.getName()) || "short".equals(type.getName()) || "float".equals(type.getName())
            || "double".equals(type.getName())) {
        return "0";
    } else if (String.class.equals(type)) {
        return "String";
    } else if (Boolean.class.equals(type) || "boolean".equals(type.getName())) {
        return "true";
    }

    return type.getName();
}