Example usage for java.lang.reflect Modifier isTransient

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

Introduction

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

Prototype

public static boolean isTransient(int mod) 

Source Link

Document

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

Usage

From source file:org.castor.jaxb.reflection.ClassInfoBuilder.java

/**
 * Checks if a field of a class is describeable or not e.g. static or
 * transient fields are not described./*from   w w w . j  a  va2 s.  c om*/
 * 
 * @param type
 *            the Class holding the field
 * @param field
 *            the field to check
 * @return true if the field should be described
 */
private boolean isDescribeable(final Class<?> type, final Field field) {
    boolean isDescribeable = true;
    Class<?> declaringClass = field.getDeclaringClass();
    if ((declaringClass != null) && !type.equals(declaringClass) && (!declaringClass.isInterface())) {
        isDescribeable = false;
    }
    if (Modifier.isStatic(field.getModifiers())) {
        isDescribeable &= false;
    }
    if (Modifier.isTransient(field.getModifiers())) {
        isDescribeable &= false;
    }
    if (field.isSynthetic()) {
        isDescribeable &= false;
    }
    return isDescribeable;
}

From source file:org.apache.apex.malhar.stream.api.impl.ApexStreamImpl.java

private void checkArguments(Operator op, Operator.InputPort inputPort, Operator.OutputPort outputPort) {
    if (op == null) {
        throw new IllegalArgumentException("Operator can not be null");
    }//  ww w .j  av  a2s.  c  o m

    boolean foundInput = inputPort == null;
    boolean foundOutput = outputPort == null;
    for (Field f : op.getClass().getFields()) {
        int modifiers = f.getModifiers();
        if (!Modifier.isPublic(modifiers) || !Modifier.isTransient(modifiers)) {
            continue;
        }
        Object obj = null;
        try {
            obj = f.get(op);
        } catch (IllegalAccessException e) {
            // NonAccessible field is not a valid port object
        }
        if (obj == outputPort) {
            foundOutput = true;
        }
        if (obj == inputPort) {
            foundInput = true;
        }
    }
    if (!foundInput || !foundOutput) {
        throw new IllegalArgumentException("Input port " + inputPort + " and/or Output port " + outputPort
                + " is/are not owned by Operator " + op);
    }

}

From source file:org.diorite.cfg.system.TemplateCreator.java

/**
 * Get template for given class.//w w w  .  j  a  v  a  2s.c om
 *
 * @param clazz    class to get template.
 * @param create   if template should be created if it don't exisit yet.
 * @param cache    if template should be saved to memory if created.
 * @param recreate if template should be force re-created even if it exisit.
 * @param <T>      Type of template class
 *
 * @return template class or null.
 */
@SuppressWarnings("unchecked")
public static <T> Template<T> getTemplate(final Class<T> clazz, final boolean create, final boolean cache,
        final boolean recreate) {
    if (!recreate) {
        final Template<T> template = (Template<T>) templateMap.get(clazz);
        if (template != null) {
            return template;
        }
        if (!create) {
            return null;
        }
    }
    Supplier<T> def = null;
    {
        final CfgDelegateDefault annotation = clazz.getAnnotation(CfgDelegateDefault.class);
        if (annotation != null) {
            final String path = annotation.value();
            final Supplier<Object> basicDelegate = ConfigField.getBasicDelegate(path);
            if (basicDelegate != null) {
                def = (Supplier<T>) basicDelegate;
            } else if (path.equalsIgnoreCase("{new}")) {
                final ConstructorInvoker constructor = DioriteReflectionUtils.getConstructor(clazz);
                def = () -> (T) constructor.invoke();
            } else {
                final int sepIndex = path.indexOf("::");
                final Class<?> targetClass;
                final String methodName;
                if (sepIndex == -1) {
                    targetClass = clazz;
                    methodName = path;
                } else {
                    try {
                        Class<?> tmpClass = DioriteReflectionUtils
                                .tryGetCanonicalClass(path.substring(0, sepIndex));
                        if (tmpClass == null) {
                            tmpClass = DioriteReflectionUtils.tryGetCanonicalClass(
                                    clazz.getPackage().getName() + "." + path.substring(0, sepIndex));
                            if (tmpClass == null) {
                                tmpClass = DioriteReflectionUtils.getNestedClass(clazz,
                                        path.substring(0, sepIndex));
                            }
                        }
                        targetClass = tmpClass;
                    } catch (final Exception e) {
                        throw new RuntimeException("Can't find class for: " + path, e);
                    }
                    methodName = path.substring(sepIndex + 2);
                }
                if (targetClass == null) {
                    throw new RuntimeException("Can't find class for delegate: " + path);
                }
                final MethodInvoker methodInvoker = DioriteReflectionUtils.getMethod(targetClass, methodName,
                        false);
                if (methodInvoker == null) {
                    final ReflectGetter<Object> reflectGetter = DioriteReflectionUtils
                            .getReflectGetter(methodName, targetClass);
                    def = () -> (T) reflectGetter.get(null);
                } else {
                    def = () -> (T) methodInvoker.invoke(null);
                }
            }
        }
    }

    final boolean allFields;
    //        final boolean superFields;
    final boolean ignoreTransient;
    final String name;
    final String header;
    final String footer;
    final Collection<String> excludedFields = new HashSet<>(5);
    {
        final CfgClass cfgInfo = clazz.getAnnotation(CfgClass.class);
        if (cfgInfo != null) {
            allFields = cfgInfo.allFields();
            //                superFields = cfgInfo.superFields();
            ignoreTransient = cfgInfo.ignoreTransient();
            name = (cfgInfo.name() != null) ? cfgInfo.name() : clazz.getSimpleName();
            Collections.addAll(excludedFields, cfgInfo.excludeFields());
        } else {
            allFields = true;
            //                superFields = true;
            ignoreTransient = true;
            name = clazz.getSimpleName();
        }
    }
    {
        final String[] comments = readComments(clazz);
        header = comments[0];
        footer = comments[1];
    }

    final Set<ConfigField> fields = new TreeSet<>();

    {
        final Collection<Class<?>> classes = new ArrayList<>(5);
        {
            Class<?> fieldsSrc = clazz;
            do {
                classes.add(fieldsSrc);
                fieldsSrc = fieldsSrc.getSuperclass();
                if (fieldsSrc == null) {
                    break;
                }
                final CfgClass cfgInfo = fieldsSrc.getAnnotation(CfgClass.class);
                if ((cfgInfo != null) && !cfgInfo.superFields()) {
                    break;
                }
            } while (!fieldsSrc.equals(Object.class));
        }

        for (final Class<?> fieldsSrc : classes) {
            int i = 0;
            for (final Field field : fieldsSrc.getDeclaredFields()) {
                if ((field.isAnnotationPresent(CfgField.class)
                        || (!field.isAnnotationPresent(CfgExclude.class) && !field.isSynthetic()
                                && (!ignoreTransient || !Modifier.isTransient(field.getModifiers()))
                                && (allFields || field.isAnnotationPresent(CfgField.class))
                                && !excludedFields.contains(field.getName())))
                        && !Modifier.isStatic(field.getModifiers())) {
                    fields.add(new ConfigField(field, i++));
                }
            }
        }
    }
    final Template<T> template = new BaseTemplate<>(name, clazz, header, footer, fields, clazz.getClassLoader(),
            def);
    if (cache) {
        templateMap.put(clazz, template);
        TemplateCreator.fields.put(clazz, template.getFieldsNameMap());
    }
    return template;
}

From source file:org.fusesource.meshkeeper.util.internal.IntrospectionSupport.java

private static void addFields(Object target, Class<?> startClass, Class<?> stopClass,
        LinkedHashMap<String, Object> map) {

    if (startClass != stopClass) {
        addFields(target, startClass.getSuperclass(), stopClass, map);
    }//from   w w w  .j  ava  2  s.c o  m

    Field[] fields = startClass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())
                || Modifier.isPrivate(field.getModifiers())) {
            continue;
        }

        try {
            field.setAccessible(true);
            Object o = field.get(target);
            if (o != null && o.getClass().isArray()) {
                try {
                    o = Arrays.asList((Object[]) o);
                } catch (Throwable e) {
                }
            }
            map.put(field.getName(), o);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

}

From source file:org.red5.io.amf.Output.java

protected boolean dontSerializeField(Class<?> objectClass, String keyName) {
    for (Class<?> clazz = objectClass; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
        try {/*from   w  w w .j  a v  a2 s  .c om*/
            Field field = clazz.getDeclaredField(keyName);
            boolean dontSerialize = field.isAnnotationPresent(DontSerialize.class);
            boolean isTransient = Modifier.isTransient(field.getModifiers());

            if (dontSerialize && log.isDebugEnabled())
                log.debug("Skipping " + field.getName() + " because its marked with @DontSerialize");
            if (isTransient)
                log.warn(
                        "Using \"transient\" to declare fields not to be serialized is deprecated and will be removed in Red5 0.8, use \"@DontSerialize\" instead.");

            return dontSerialize || isTransient;
        } catch (NoSuchFieldException nfe) {
            // Ignore this exception and use the default behaviour
            log.debug("writeObject caught NoSuchFieldException");
        }
    }

    return false;
}

From source file:org.apache.openjpa.meta.FieldMetaData.java

/**
 * Supply the backing member object; this allows us to utilize
 * parameterized type information if available.
 * Sets the access style of this receiver based on whether the given 
 * member represents a field or getter method.
 *///  www. j av  a  2  s.  c  o  m
public void backingMember(Member member) {
    if (member == null)
        return;
    if (Modifier.isTransient(member.getModifiers()))
        _transient = true;

    _backingMember = new MemberProvider(member);

    Class<?> type;
    Class<?>[] types;
    if (member instanceof Field) {
        Field f = (Field) member;
        type = f.getType();
        types = JavaVersions.getParameterizedTypes(f);
        setAccessType(AccessCode.FIELD);
    } else {
        Method meth = (Method) member;
        type = meth.getReturnType();
        types = JavaVersions.getParameterizedTypes(meth);
        setAccessType(AccessCode.PROPERTY);
    }

    setDeclaredType(type);
    if (Collection.class.isAssignableFrom(type) && _elem.getDeclaredType() == Object.class
            && types.length == 1) {
        _elem.setDeclaredType(types[0]);
    } else if (Map.class.isAssignableFrom(type) && types.length == 2) {
        if (_key.getDeclaredType() == Object.class)
            _key.setDeclaredType(types[0]);
        if (_elem.getDeclaredType() == Object.class)
            _elem.setDeclaredType(types[1]);
    }
}

From source file:wwutil.jsoda.Jsoda.java

/** Register a POJO model class.  Register the model to use the dbtype, ignoring the model's dbtype annotation. */
public <T> void registerModel(Class<T> modelClass, DbType dbtype) throws JsodaException {
    try {//w w  w . j ava  2s. co  m
        String modelName = getModelName(modelClass);
        List<Field> allFields = ReflectUtil.getAllFields(modelClass);
        Field idField = toKeyField(modelClass, allFields, false);
        Field rangeField = toKeyField(modelClass, allFields, true);

        List<Field> savedFields = FnUtil.filter(allFields, new PredicateFn<Field>() {
            public boolean apply(Field f) {
                return Modifier.isTransient(f.getModifiers()) || // skip transient field
                ReflectUtil.hasAnnotation(f, Transient.class);
            }
        });
        List<Field> dbFields = FnUtil.filter(savedFields, new PredicateFn<Field>() {
            public boolean apply(Field f) {
                return ReflectUtil.hasAnnotation(f, S3Field.class); // skip S3 field
            }
        });
        List<Field> s3Fields = FnUtil.filter(savedFields, new PredicateFn<Field>() {
            public boolean apply(Field f) {
                return !ReflectUtil.hasAnnotation(f, S3Field.class); // skip non-S3 field
            }
        });

        validateClass(modelClass);
        validateFields(modelClass, idField, rangeField);

        modelClasses.put(modelName, modelClass);
        modelDb.put(modelName, toDbService(modelClass, dbtype));
        modelTables.put(modelName, toTableName(modelClass));
        modelIdFields.put(modelName, idField);
        if (rangeField != null)
            modelRangeFields.put(modelName, rangeField);
        Field versionField = ReflectUtil.findAnnotatedField(modelClass, VersionLocking.class);
        if (versionField != null)
            modelVersionFields.put(modelName, versionField);
        toCachePolicy(modelName, modelClass);
        modelAllFieldMap.put(modelName, toFieldMap(allFields));
        modelDbFieldMap.put(modelName, toFieldMap(dbFields));
        modelAttrFieldMap.put(modelName, toAttrFieldMap(dbFields));
        modelFieldAttrMap.put(modelName, toFieldAttrMap(dbFields));
        modelS3FieldMap.put(modelName, toFieldMap(s3Fields));
        modelCacheByFields.put(modelName, toCacheByFields(dbFields)); // Build CacheByFields on all db fields, including the Id field
        toAnnotatedMethods(modelName, modelClass);
        modelDao.put(modelName, new Dao<T>(modelClass, this));
        modelS3Dao.put(modelName, new S3Dao<T>(modelClass, this));
        modelEUtil.put(modelName, new EUtil<T>(modelClass, this));

        preStore1Registry.checkModelOnFields(modelAllFieldMap.get(modelName));
        preStore2Registry.checkModelOnFields(modelAllFieldMap.get(modelName));
        validationRegistry.checkModelOnFields(modelAllFieldMap.get(modelName));
        postLoadRegistry.checkModelOnFields(modelAllFieldMap.get(modelName));

    } catch (JsodaException je) {
        throw je;
    } catch (Exception e) {
        throw new JsodaException("Failed to register model class", e);
    }
}

From source file:org.romaframework.aspect.persistence.datanucleus.jdo.JDOPersistenceHelper.java

protected QueryByFilter buildQueryByFilter(QueryByExample iQuery) {
    if (log.isDebugEnabled())
        log.debug("[JDOPersistenceAspect.queryByExample] Class: " + iQuery.getCandidateClass()
                + " filter object: " + iQuery);

    // TODO Use SchemaClassReflection to use method/field getters and setters

    // EXTRACT QUERY BASED ON FILER OBJECT
    QueryByFilter filter = new QueryByFilter(iQuery.getCandidateClass());
    filter.setRangeFrom(iQuery.getRangeFrom(), iQuery.getRangeTo());
    filter.setSubClasses(iQuery.isSubClasses());
    filter.setMode(iQuery.getMode());/*  w  w  w .  j a  v  a2s  .c o  m*/
    filter.setStrategy(iQuery.getStrategy());

    if (iQuery.getFilter() != null) {
        Field[] fields = SchemaHelper.getFields(iQuery.getCandidateClass());
        Object fieldValue;
        QueryOperator operator = null;
        for (int i = 0; i < fields.length; ++i) {
            try {
                if (Modifier.isStatic(fields[i].getModifiers())
                        || Modifier.isTransient(fields[i].getModifiers()))
                    // JUMP STATIC AND TRANSIENT FIELDS
                    continue;

                if (fields[i].getName().startsWith("jdo"))
                    // IGNORE ALL JDO FIELDS
                    continue;

                if (!fields[i].isAccessible())
                    fields[i].setAccessible(true);

                fieldValue = fields[i].get(iQuery.getFilter());
                if (fieldValue != null) {
                    if (fieldValue instanceof Collection<?> || fieldValue instanceof Map<?, ?>)
                        continue;
                    if (fieldValue instanceof String && ((String) fieldValue).length() == 0)
                        // EMPTY STRING, IGNORE FOR FILTERING
                        continue;

                    if (fields[i].getType().equals(String.class))
                        operator = QueryByFilter.FIELD_LIKE;
                    else
                        operator = QueryByFilter.FIELD_EQUALS;

                    // INSERT INTO QUERY PREDICATE
                    filter.addItem(fields[i].getName(), operator, fieldValue);
                }
            } catch (Exception e) {
                log.error("[JDOPersistenceAspect.queryByExample]", e);
            }
        }
    }

    QueryByFilter addFilter = iQuery.getAdditionalFilter();
    if (addFilter != null) {
        filter.setSubClasses(addFilter.isSubClasses());

        // COPY ALL ITEMS TO THE MAIN FILTER
        for (Iterator<QueryByFilterItem> it = addFilter.getItemsIterator(); it.hasNext();) {
            filter.addItem(it.next());
        }

        // COPY ALL ORDER CLAUSES TO THE MAIN FILTER
        for (Iterator<QueryByFilterOrder> it = addFilter.getOrdersIterator(); it.hasNext();) {
            filter.addOrder(it.next());
        }
    }
    return filter;
}

From source file:org.red5.io.amf3.Output.java

/** {@inheritDoc} */
@Override/* w  w w  .j  a va 2 s. c o  m*/
protected void writeArbitraryObject(Object object, Serializer serializer) {
    Class<?> objectClass = object.getClass();
    String className = objectClass.getName();
    if (className.startsWith("org.red5.compatibility.")) {
        // Strip compatibility prefix from classname
        className = className.substring(23);
    }

    // If we need to serialize class information...
    if (!objectClass.isAnnotationPresent(Anonymous.class)) {
        putString(className);
    } else {
        putString("");
    }

    // Store key/value pairs
    amf3_mode += 1;
    // Get public field values
    Map<String, Object> values = new HashMap<String, Object>();
    // Iterate thru fields of an object to build "name-value" map from it
    for (Field field : objectClass.getFields()) {
        if (field.isAnnotationPresent(DontSerialize.class)) {
            if (log.isDebugEnabled()) {
                log.debug("Skipping " + field.getName() + " because its marked with @DontSerialize");
            }
            continue;
        } else {
            int modifiers = field.getModifiers();
            if (Modifier.isTransient(modifiers)) {
                log.warn("Using \"transient\" to declare fields not to be serialized is "
                        + "deprecated and will be removed in Red5 0.8, use \"@DontSerialize\" instead.");
                continue;
            }
        }

        Object value;
        try {
            // Get field value
            value = field.get(object);
        } catch (IllegalAccessException err) {
            // Swallow on private and protected properties access exception
            continue;
        }
        // Put field to the map of "name-value" pairs
        values.put(field.getName(), value);
    }

    // Output public values
    Iterator<Map.Entry<String, Object>> it = values.entrySet().iterator();
    // Iterate thru map and write out properties with separators
    while (it.hasNext()) {
        Map.Entry<String, Object> entry = it.next();
        // Write out prop name
        putString(entry.getKey());
        // Write out
        serializer.serialize(this, entry.getValue());
    }
    amf3_mode -= 1;
    // Write out end of object marker
    putString("");
}

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

/**
 * /*from   ww w.jav  a  2s.c  o  m*/
 * @param entity
 * @param includeTransient
 * @return
 * @throws IllegalArgumentException
 */
public List<MarshalledField> marshallOut(Object entity, boolean includeTransient)
        throws IllegalArgumentException {

    TreeSet<MarshalledField> fields = new TreeSet<MarshalledField>();

    if (entity == null) {
        for (Map.Entry<Field, Converter> ent : instructions.entrySet()) {
            fields.add(new MarshalledField(ent.getKey().getName()));
        }
        return new LinkedList<MarshalledField>(fields);
    }

    log.debug("Marshalling out instance of " + entity.getClass().getSimpleName());

    Field field;
    Converter converter;
    Object value;
    Method getter;

    boolean error = false;

    for (Map.Entry<Field, Converter> ent : instructions.entrySet()) {

        error = false;

        field = ent.getKey();
        converter = ent.getValue();
        value = null;

        log.debug("Converting field " + field.getName());

        if ((field.isAnnotationPresent(Transient.class) || Modifier.isTransient(field.getModifiers()))
                && !includeTransient)
            continue;

        try {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            if (field.isAccessible()) {
                value = convertNull(field.get(entity));
            } else {
                error = true;
            }
        } catch (IllegalAccessException iae) {
            log.error("Unable to access " + entity.getClass().getSimpleName() + "." + field.getName()
                    + " directly.", iae);
            error = true;
        }

        if (error) {
            error = false;
            try {
                getter = converter.getGetter();
                if (getter != null) {
                    if (!getter.isAccessible()) {
                        getter.setAccessible(true);
                    }
                    if (getter.isAccessible()) {
                        value = convertNull(getter.invoke(entity));
                    } else {
                        error = true;
                    }
                } else {
                    error = true;
                }
            } catch (IllegalAccessException iae) {
                log.error("Error accessing getter for field " + entity.getClass().getSimpleName() + "."
                        + field.getName(), iae);
                error = true;
            } catch (InvocationTargetException ite) {
                log.error("Error invoking getter for field " + entity.getClass().getSimpleName() + "."
                        + field.getName(), ite);
                error = true;
            }
        }

        if (error) {
            // if there was an error, then we weren't able to access the field,
            // so set the value to be displayed to "Inaccessible!" and override
            // the converter readonly value to make sure the display doesn't let
            // the user edit an inaccessible field.
            converter.setReadOnly(true);
            fields.add(new MarshalledField(field.getName(), "Inaccessible!", converter));
        } else {
            fields.add(new MarshalledField(field.getName(), value, converter));
        }
    }

    return new LinkedList<MarshalledField>(fields);
}