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.fastmongo.odm.dbobject.mapping.core.ConverterHelper.java

/**
 * Returns all fields of the given class.
 * <p/>/*from w w  w  . ja va 2  s  . c  o m*/
 * Skips transient and static fields.
 *
 * @param clazz the class.
 */
public static List<Field> getClassFields(Class<?> clazz) {
    List<Field> fields = CLASS_FIELDS.get(clazz);
    if (fields == null) {
        final List<Field> newFields = new ArrayList<>();
        ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() {
            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                newFields.add(field);
            }
        }, new ReflectionUtils.FieldFilter() {
            @Override
            public boolean matches(Field field) {
                return !Modifier.isTransient(field.getModifiers()) && !Modifier.isStatic(field.getModifiers());
            }
        });
        fields = Collections.unmodifiableList(newFields);
        CLASS_FIELDS.put(clazz, fields);
    }

    return fields;
}

From source file:org.apache.flink.api.java.Utils.java

private static String getGenericTypeTree(Class<?> type, int indent) {
    String ret = "";
    for (Field field : type.getDeclaredFields()) {
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
            continue;
        }/*from   w ww .  j a  v a 2  s. c o m*/
        ret += StringUtils.repeat(' ', indent) + field.getName() + ":" + field.getType().getName()
                + (field.getType().isEnum() ? " (is enum)" : "") + "\n";
        if (!field.getType().isPrimitive()) {
            ret += getGenericTypeTree(field.getType(), indent + 4);
        }
    }
    return ret;
}

From source file:com.googlecode.ehcache.annotations.key.AbstractDeepCacheKeyGenerator.java

/**
 * Calls {@link #shouldReflect(Object)} to determine if the object needs to be reflected on to
 * generate a good key. If so {@link AccessibleObject#setAccessible(AccessibleObject[], boolean)} is
 * used to enable access to private, protected and default fields. Each non-transient, non-static field
 * has {@link #deepHashCode(Object, Object)} called on it.
 *//*from ww  w . java 2  s. c om*/
protected final void reflectionDeepHashCode(G generator, final Object element) {
    //Special objects which shouldn't be reflected on due to lack of interesting fields
    if (element instanceof Class<?>) {
        this.append(generator, element);
        return;
    }

    //Determine if the element should be reflected on
    if (!this.shouldReflect(element)) {
        this.append(generator, element);
        return;
    }

    //Accumulate the data that makes up the object being reflected on so it can be recursed on as a single grouping of data
    final List<Object> reflectiveObject = new LinkedList<Object>();

    //Write out the target class so that two classes with the same fields can't collide
    reflectiveObject.add(element.getClass());

    try {
        for (Class<?> targetClass = element.getClass(); targetClass != null; targetClass = targetClass
                .getSuperclass()) {
            final Field[] fields = targetClass.getDeclaredFields();
            AccessibleObject.setAccessible(fields, true);

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

                //Ignore static and transient fields
                if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
                    final Object fieldValue = field.get(element);
                    reflectiveObject.add(fieldValue);
                }
            }
        }
    } catch (IllegalAccessException exception) {
        ReflectionUtils.handleReflectionException(exception);
    }

    this.deepHashCode(generator, reflectiveObject);
}

From source file:org.vulpe.model.dao.impl.db4o.AbstractVulpeBaseDAODB4O.java

/**
 * Repair relationship of entity.//from   w  ww.j  a  v  a  2 s . com
 *
 * @param <T>
 * @param entity
 */
protected <T> void repairRelationship(final T entity, final ObjectContainer container) {
    emptyToNull(entity);
    for (final Field field : VulpeReflectUtil.getFields(entity.getClass())) {
        if (!Modifier.isTransient(field.getModifiers())) {
            final Object value = VulpeReflectUtil.getFieldValue(entity, field.getName());
            if (value != null) {
                if (VulpeEntity.class.isAssignableFrom(field.getType())) {
                    try {
                        final VulpeEntity<Long> valueEntity = (VulpeEntity) value;
                        if (valueEntity.getId() != null) {
                            final VulpeEntity<Long> newEntity = (VulpeEntity<Long>) field.getType()
                                    .newInstance();
                            newEntity.setId(valueEntity.getId());
                            final ObjectSet objectSet = getObjectContainer().queryByExample(newEntity);
                            if (objectSet.hasNext()) {
                                PropertyUtils.setProperty(entity, field.getName(), objectSet.next());
                            }
                        } else {
                            if (value.getClass().isAnnotationPresent(CreateIfNotExist.class)) {
                                simpleMerge(container, value);
                            } else {
                                PropertyUtils.setProperty(entity, field.getName(), null);
                            }
                        }
                    } catch (Exception e) {
                        LOG.error(e.getMessage());
                    }
                } else if (Collection.class.isAssignableFrom(field.getType())) {
                    final Collection details = (Collection) value;
                    for (final Object object : details) {
                        if (object != null) {
                            if (VulpeEntity.class.isAssignableFrom(object.getClass())) {
                                try {
                                    final String attributeName = VulpeStringUtil
                                            .lowerCaseFirst(entity.getClass().getSimpleName());
                                    final VulpeEntity<Long> detail = (VulpeEntity<Long>) object;
                                    repair(detail, container);
                                    PropertyUtils.setProperty(detail, attributeName, entity);
                                    if (detail.getId() == null) {
                                        detail.setId(getId(detail));
                                    } else {
                                        final VulpeEntity<Long> valueEntity = (VulpeEntity) entity;
                                        final VulpeEntity<Long> newEntity = (VulpeEntity<Long>) entity
                                                .getClass().newInstance();
                                        newEntity.setId(valueEntity.getId());
                                        final VulpeEntity<Long> newDetailEntity = (VulpeEntity<Long>) object
                                                .getClass().newInstance();
                                        newDetailEntity.setId(detail.getId());
                                        PropertyUtils.setProperty(newDetailEntity, attributeName, newEntity);
                                        final ObjectSet objectSet = getObjectContainer()
                                                .queryByExample(newDetailEntity);
                                        if (objectSet.hasNext()) {
                                            final VulpeEntity<Long> persitedDetail = (VulpeEntity<Long>) objectSet
                                                    .get(0);
                                            container.ext().bind(detail, container.ext().getID(persitedDetail));
                                            container.store(detail);
                                        }
                                    }
                                } catch (Exception e) {
                                    LOG.error(e.getMessage());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

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

/**
 * Checks if a method is {@link Transient} either by specifying the transient modifier
 * or the {@link Transient} annotation.// w w  w.  j ava  2s.c o m
 * 
 * @param method
 *          the method
 * @return true, if is transient
 */
public static boolean isTransient(Method method) {
    if (Modifier.isTransient(method.getModifiers())) {
        return true;
    }

    if (method.isAnnotationPresent(Transient.class)) {
        return true;
    }

    return false;
}

From source file:com.browseengine.bobo.serialize.JSONSerializer.java

public static JSONObject serializeJSONObject(JSONSerializable obj)
        throws JSONSerializationException, JSONException {
    if (obj instanceof JSONExternalizable) {
        return ((JSONExternalizable) obj).toJSON();
    }//from  ww  w.j  a  v a 2s  .  co  m

    JSONObject jsonObj = new JSONObject();
    Class clz = obj.getClass();
    Field[] fields = clz.getDeclaredFields();

    for (int i = 0; i < fields.length; ++i) {
        fields[i].setAccessible(true);
        int modifiers = fields[i].getModifiers();
        if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) {
            String name = fields[i].getName();
            Class type = fields[i].getType();

            try {
                Object value = fields[i].get(obj);

                if (type.isArray() && value != null) {
                    int len = Array.getLength(value);

                    Class cls = type.getComponentType();

                    JSONArray array = new JSONArray();

                    for (int k = 0; k < len; ++k) {
                        dumpObject(array, cls, value, k);
                    }
                    jsonObj.put(name, array);
                } else {
                    dumpObject(jsonObj, fields[i], obj);
                }
            } catch (Exception e) {
                throw new JSONSerializationException(e.getMessage(), e);
            }
        }
    }

    return jsonObj;
}

From source file:org.lmn.fc.common.utilities.pending.Utilities.java

/***********************************************************************************************
 * Show the Member Modifiers./*from  w ww . j  ava 2 s  .  c o m*/
 *
 * @param member
 *
 * @return String
 */

public static String showModifiers(final Member member) {
    final int modifiers;
    final StringBuffer buffer;

    buffer = new StringBuffer();

    if (member != null) {
        modifiers = member.getModifiers();

        if (Modifier.isAbstract(modifiers)) {
            buffer.append("Abstract ");
        }

        if (Modifier.isFinal(modifiers)) {
            buffer.append("Final ");
        }

        if (Modifier.isInterface(modifiers)) {
            buffer.append("Interface ");
        }

        if (Modifier.isNative(modifiers)) {
            buffer.append("Native ");
        }

        if (Modifier.isPrivate(modifiers)) {
            buffer.append("Private ");
        }

        if (Modifier.isProtected(modifiers)) {
            buffer.append("Protected ");
        }

        if (Modifier.isPublic(modifiers)) {
            buffer.append("Public ");
        }

        if (Modifier.isStatic(modifiers)) {
            buffer.append("Static ");
        }

        if (Modifier.isStrict(modifiers)) {
            buffer.append("Strict ");
        }

        if (Modifier.isSynchronized(modifiers)) {
            buffer.append("Synchronized ");
        }

        if (Modifier.isTransient(modifiers)) {
            buffer.append("Transient ");
        }

        if (Modifier.isVolatile(modifiers)) {
            buffer.append("Volatile ");
        }
    }

    return (buffer.toString().trim());
}

From source file:com.px100systems.util.serialization.SerializationDefinition.java

private SerializationDefinition(Class<?> cls) {
    definitions.put(cls, this);

    if (cls.getName().startsWith("java"))
        throw new RuntimeException("System classes are not supported: " + cls.getSimpleName());

    try {/*from w w  w  .j a va2  s  .c  o  m*/
        constructor = cls.getConstructor();
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("Missing no-arg constructor: " + cls.getSimpleName());
    }

    serializingSetter = ReflectionUtils.findMethod(cls, "setSerializing", boolean.class);

    for (Class<?> c = cls; c != null && !c.equals(Object.class); c = c.getSuperclass()) {
        for (Field field : c.getDeclaredFields()) {
            if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()))
                continue;

            FieldDefinition fd = new FieldDefinition();
            fd.name = field.getName();

            fd.type = field.getType();
            if (fd.type.isPrimitive())
                throw new RuntimeException("Primitives are not supported: " + fd.type.getSimpleName());

            Calculated calc = field.getAnnotation(Calculated.class);

            if (!fd.type.equals(Integer.class) && !fd.type.equals(Long.class) && !fd.type.equals(Double.class)
                    && !fd.type.equals(Boolean.class) && !fd.type.equals(Date.class)
                    && !fd.type.equals(String.class))
                if (fd.type.equals(List.class) || fd.type.equals(Set.class)) {
                    SerializedCollection sc = field.getAnnotation(SerializedCollection.class);
                    if (sc == null)
                        throw new RuntimeException(
                                cls.getSimpleName() + "." + fd.name + " is missing @SerializedCollection");

                    if (calc != null)
                        throw new RuntimeException(cls.getSimpleName() + "." + fd.name
                                + " cannot have a calculator because it is a collection");

                    fd.collectionType = sc.type();
                    fd.primitive = fd.collectionType.equals(Integer.class)
                            || fd.collectionType.equals(Long.class) || fd.collectionType.equals(Double.class)
                            || fd.collectionType.equals(Boolean.class) || fd.collectionType.equals(Date.class)
                            || fd.collectionType.equals(String.class);
                    if (!fd.primitive) {
                        if (cls.getName().startsWith("java"))
                            throw new RuntimeException(cls.getSimpleName() + "." + fd.name
                                    + ": system collection types are not supported: "
                                    + fd.collectionType.getSimpleName());

                        if (!definitions.containsKey(fd.collectionType))
                            new SerializationDefinition(fd.collectionType);
                    }
                } else {
                    if (cls.getName().startsWith("java"))
                        throw new RuntimeException(
                                "System classes are not supported: " + fd.type.getSimpleName());

                    if (!definitions.containsKey(fd.type))
                        new SerializationDefinition(fd.type);
                }
            else
                fd.primitive = true;

            try {
                fd.accessor = c.getMethod(PropertyAccessor.methodName("get", fd.name));
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing getter");
            }

            try {
                fd.mutator = c.getMethod(PropertyAccessor.methodName("set", fd.name), fd.type);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing setter");
            }

            if (calc != null)
                fd.calculator = new SpelExpressionParser().parseExpression(calc.value());

            fields.add(fd);
        }

        for (Method method : c.getDeclaredMethods())
            if (Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers())
                    && method.getName().startsWith("get")
                    && method.isAnnotationPresent(SerializedGetter.class)) {
                FieldDefinition fd = new FieldDefinition();
                fd.name = method.getName().substring(3);
                fd.name = fd.name.substring(0, 1).toLowerCase() + fd.name.substring(1);
                fd.type = method.getReturnType();
                fd.primitive = fd.type != null && (fd.type.equals(Integer.class) || fd.type.equals(Long.class)
                        || fd.type.equals(Double.class) || fd.type.equals(Boolean.class)
                        || fd.type.equals(Date.class) || fd.type.equals(String.class));

                if (!fd.primitive)
                    throw new RuntimeException("Not compact-serializable getter type: "
                            + (fd.type == null ? "void" : fd.type.getSimpleName()));

                fd.accessor = method;
                gettersOnly.add(fd);
            }
    }
}

From source file:HashCodeBuilder.java

/**
 * This method uses reflection to build a valid hash code. 
 * <p>//from ww w . j a  v a  2 s . com
 * It uses Field.setAccessible to gain access to private fields. This means
 * that it will throw a security exception if run under a security manger, if
 * the permissions are not set up.
 * It is also not as efficient as testing explicitly. 
 * If the TestTransients parameter is set to true, transient members will be
 * tested, otherwise they are ignored, as they are likely derived fields, and
 * not part of the value of the object. 
 * Static fields will not be tested.
 * <p>
 * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally
 * these should be different for each class, however this is not vital.
 * Prime numbers are preferred, especially for the multiplier.
 * 
 * @param initialNonZeroOddNumber
 * @param multiplierNonZeroOddNumber
 * @param object  the object to create a hash code for
 * @param testTransients  whether to include transient fields
 * @return int hash code
 * @throws IllegalArgumentException if the object is null
 * @throws IllegalArgumentException if the number is zero or even
 */
public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object,
        boolean testTransients) {

    if (object == null) {
        throw new IllegalArgumentException("The object to build a hash code for must not be null");
    }
    HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber);
    Field[] fields = object.getClass().getDeclaredFields();
    Field.setAccessible(fields, true);
    for (int i = 0; i < fields.length; ++i) {
        Field f = fields[i];
        if (testTransients || !Modifier.isTransient(f.getModifiers())) {
            if (!Modifier.isStatic(f.getModifiers())) {
                try {
                    hashCodeBuilder.append(f.get(object));
                } catch (IllegalAccessException e) {
                    //this can't happen. Would get a Security exception instead
                    //throw a runtime exception in case the impossible happens.
                    throw new InternalError("Unexpected IllegalAccessException");
                }
            }
        }
    }
    return hashCodeBuilder.toHashCode();
}

From source file:py.una.pol.karaku.dao.entity.interceptors.InterceptorHandler.java

/**
 * Verifica si un field puede ser asignable. Se define un fiel asignable
 * como aquel que no es estatico, final.
 * //from  w  w  w .j a v a 2 s.  c  o  m
 * Como nota general tener en cuenta que un campo que no es String es
 * inmediatamente no asignable
 * 
 * @param field
 *            a ser evaluado
 * @return <code>true</code> si es asignable, <code>false</code> en caso
 *         contrario
 */
private boolean isAssignable(Field field) {

    int modifier = field.getModifiers();
    if (Modifier.isFinal(modifier)) {
        return false;
    }
    if (Modifier.isStatic(modifier)) {
        return false;
    }
    if (Modifier.isTransient(modifier)) {
        return false;
    }
    return field.getAnnotation(Transient.class) == null;
}