Example usage for java.lang.reflect Modifier isStatic

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

Introduction

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

Prototype

public static boolean isStatic(int mod) 

Source Link

Document

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

Usage

From source file:org.springmodules.cache.util.Reflections.java

/**
 * <p>/*from w w w  .j  a  v a2 s.c  om*/
 * This method uses reflection to build a valid hash code.
 * </p>
 *
 * <p>
 * It uses <code>AccessibleObject.setAccessible</code> to gain access to
 * private fields. This means that it will throw a security exception if run
 * under a security manager, if the permissions are not set up correctly. It
 * is also not as efficient as testing explicitly.
 * </p>
 *
 * <p>
 * Transient members will not be used, as they are likely derived fields,
 * and not part of the value of the <code>Object</code>.
 * </p>
 *
 * <p>
 * Static fields will not be tested. Superclass fields will be included.
 * </p>
 *
 * @param obj
 *          the object to create a <code>hashCode</code> for
 * @return the generated hash code, or zero if the given object is
 *         <code>null</code>
 */
public static int reflectionHashCode(Object obj) {
    if (obj == null)
        return 0;

    Class targetClass = obj.getClass();
    if (Objects.isArrayOfPrimitives(obj) || Objects.isPrimitiveOrWrapper(targetClass)) {
        return Objects.nullSafeHashCode(obj);
    }

    if (targetClass.isArray()) {
        return reflectionHashCode((Object[]) obj);
    }

    if (obj instanceof Collection) {
        return reflectionHashCode((Collection) obj);
    }

    if (obj instanceof Map) {
        return reflectionHashCode((Map) obj);
    }

    // determine whether the object's class declares hashCode() or has a
    // superClass other than java.lang.Object that declares hashCode()
    Class clazz = (obj instanceof Class) ? (Class) obj : obj.getClass();
    Method hashCodeMethod = ReflectionUtils.findMethod(clazz, "hashCode", new Class[0]);

    if (hashCodeMethod != null) {
        return obj.hashCode();
    }

    // could not find a hashCode other than the one declared by java.lang.Object
    int hash = INITIAL_HASH;

    try {
        while (targetClass != null) {
            Field[] fields = targetClass.getDeclaredFields();
            AccessibleObject.setAccessible(fields, true);

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

                if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
                    hash = MULTIPLIER * hash + reflectionHashCode(field.get(obj));
                }
            }
            targetClass = targetClass.getSuperclass();
        }
    } catch (IllegalAccessException exception) {
        // ///CLOVER:OFF
        ReflectionUtils.handleReflectionException(exception);
        // ///CLOVER:ON
    }

    return hash;
}

From source file:org.mayocat.search.elasticsearch.AbstractGenericEntityIndexDocumentPurveyor.java

protected Map<String, Object> extractSourceFromEntity(Entity entity, Tenant tenant) {
    Map<String, Object> source = Maps.newHashMap();
    Map<String, Object> properties = Maps.newHashMap();

    boolean hasClassLevelIndexAnnotation = entity.getClass().isAnnotationPresent(Index.class);

    for (Field field : entity.getClass().getDeclaredFields()) {
        boolean isAccessible = field.isAccessible();
        try {/*from w w w.j  a va2  s  .co  m*/
            if (Modifier.isStatic(field.getModifiers())) {
                // we're not interested in static fields like serialVersionUid (or any other static field)
                continue;
            }

            if (Identifiable.class.isAssignableFrom(entity.getClass()) && field.getName().equals("id")) {
                // do not index the id of identifiable under properties
                continue;
            }

            if (Slug.class.isAssignableFrom(entity.getClass()) && field.getName().equals("slug")) {
                // do not index the slug of slugs under properties
                // (it is indexed as a top level property)
                continue;
            }

            field.setAccessible(true);
            boolean searchIgnoreFlag = field.isAnnotationPresent(DoNotIndex.class);
            boolean indexFlag = field.isAnnotationPresent(Index.class);

            if ((hasClassLevelIndexAnnotation || indexFlag) && !searchIgnoreFlag) {
                if (field.get(entity) != null) {
                    Class fieldClass = field.get(entity).getClass();

                    if (isAddonField(fieldClass, field)) {

                        // Treat addons differently.
                        // They're not located in the "properties" object like the other entity properties,
                        // but they're stored in their own "addon" object

                        Association<Map<String, AddonGroup>> addons = (Association<Map<String, AddonGroup>>) field
                                .get(entity);
                        if (addons.isLoaded()) {
                            source.put("addons", extractAddons(addons.get()));
                        }
                    } else if (BigDecimal.class.isAssignableFrom(fieldClass)) {

                        // Convert big decimal to double value

                        properties.put(field.getName(), ((BigDecimal) field.get(entity)).doubleValue());
                    } else {

                        // General case o>

                        properties.put(field.getName(), field.get(entity));
                    }
                } else {
                    properties.put(field.getName(), null);
                }
            }
        } catch (IllegalAccessException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (JsonMappingException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (JsonParseException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (JsonProcessingException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (IOException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } finally {
            field.setAccessible(isAccessible);
        }
    }

    source.put("properties", properties);

    if (HasFeaturedImage.class.isAssignableFrom(entity.getClass())) {
        HasFeaturedImage hasFeaturedImage = (HasFeaturedImage) entity;
        if (hasFeaturedImage.getFeaturedImageId() != null) {
            Attachment attachment = attachmentStore.findAndLoadById(hasFeaturedImage.getFeaturedImageId());
            if (attachment != null) {
                Map<String, Object> imageMap = Maps.newHashMap();
                imageMap.put("url", entityURLFactory.create(attachment, tenant));
                imageMap.put("title", attachment.getTitle());
                imageMap.put("extension", attachment.getExtension());
                source.put("featuredImage", imageMap);
            }
        }
    }

    source.put("url", entityURLFactory.create(entity, tenant).toString());
    source.put("api_url", entityURLFactory.create(entity, tenant, URLType.API).toString());
    source.put("slug", entity.getSlug());

    return source;
}

From source file:Main.java

public static boolean equals(Object target, Object o) {
    if (target == o)
        return true;
    if (target == null || o == null)
        return false;
    if (!target.getClass().equals(o.getClass()))
        return false;

    Class<?> current = target.getClass();
    do {/*from   w ww.j  av a 2 s . c  o  m*/
        for (Field f : current.getDeclaredFields()) {
            if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers())
                    || f.isSynthetic()) {
                continue;
            }

            Object self;
            Object other;
            try {
                f.setAccessible(true);
                self = f.get(target);
                other = f.get(o);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException(e);
            }
            if (self == null) {
                if (other != null)
                    return false;
            } else if (self.getClass().isArray()) {
                if (self.getClass().equals(boolean[].class)) {
                    if (!Arrays.equals((boolean[]) self, (boolean[]) other))
                        return false;
                } else if (self.getClass().equals(char[].class)) {
                    if (!Arrays.equals((char[]) self, (char[]) other))
                        return false;
                } else if (self.getClass().equals(byte[].class)) {
                    if (!Arrays.equals((byte[]) self, (byte[]) other))
                        return false;
                } else if (self.getClass().equals(short[].class)) {
                    if (!Arrays.equals((short[]) self, (short[]) other))
                        return false;
                } else if (self.getClass().equals(int[].class)) {
                    if (!Arrays.equals((int[]) self, (int[]) other))
                        return false;
                } else if (self.getClass().equals(long[].class)) {
                    if (!Arrays.equals((long[]) self, (long[]) other))
                        return false;
                } else if (self.getClass().equals(float[].class)) {
                    if (!Arrays.equals((float[]) self, (float[]) other))
                        return false;
                } else if (self.getClass().equals(double[].class)) {
                    if (!Arrays.equals((double[]) self, (double[]) other))
                        return false;
                } else {
                    if (!Arrays.equals((Object[]) self, (Object[]) other))
                        return false;
                }
            } else if (!self.equals(other)) {
                return false;
            }
        }
        current = current.getSuperclass();
    } while (!Object.class.equals(current));

    return true;
}

From source file:net.ostis.sc.memory.SCKeynodesBase.java

protected static void init(SCSession session, Class<? extends SCKeynodesBase> klass) {
    if (log.isDebugEnabled())
        log.debug("Start retrieving keynodes for " + klass);

    try {/*  w w w . j av a  2s . co  m*/
        //
        // Search default segment for keynodes
        //
        SCSegment defaultSegment = null;
        {
            DefaultSegment annotation = klass.getAnnotation(DefaultSegment.class);
            if (annotation != null) {
                defaultSegment = session.openSegment(annotation.value());
                Validate.notNull(defaultSegment, "Default segment \"{0}\" not found", annotation.value());
                klass.getField(annotation.fieldName()).set(null, defaultSegment);
            }
        }

        Field[] fields = klass.getFields();
        for (Field field : fields) {
            int modifiers = field.getModifiers();

            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
                Class<?> type = field.getType();
                if (type.equals(SCSegment.class)) {
                    //
                    // We have segment field. Load segment by uri.
                    //
                    SegmentURI annotation = field.getAnnotation(SegmentURI.class);

                    if (annotation != null) {
                        String uri = annotation.value();
                        SCSegment segment = session.openSegment(uri);
                        field.set(null, segment);
                    } else {
                        // May be it already has value?
                        if (log.isWarnEnabled()) {
                            if (field.get(null) == null)
                                log.warn(field + " doesn't have value");
                        }
                    }
                } else {
                    if (!(checkKeynode(session, defaultSegment, field) || checkKeynodeURI(session, field)
                            || checkKeynodesNumberPatternURI(session, klass, field))) {

                        if (log.isWarnEnabled()) {
                            if (field.get(null) == null)
                                log.warn(field + " doesn't have annotations and value");
                        }

                    }
                }
            }
        }
    } catch (Exception e) {
        // TODO: handle
        e.printStackTrace();
    }
}

From source file:com.excilys.ebi.utils.spring.log.slf4j.InjectLoggerAnnotationBeanPostProcessor.java

/**
 * Processes a bean's fields for injection if it has a {@link InjectLogger}
 * annotation.//from www  .  j  a v  a  2  s  .  c  o  m
 */
protected void processLogger(final Object bean) {
    final Class<?> clazz = bean.getClass();

    ReflectionUtils.doWithFields(clazz, new FieldCallback() {
        public void doWith(Field field) {
            Annotation annotation = field.getAnnotation(InjectLogger.class);

            if (annotation != null) {
                int modifiers = field.getModifiers();
                Assert.isTrue(!Modifier.isStatic(modifiers),
                        "InjectLogger annotation is not supported on static fields");
                Assert.isTrue(!Modifier.isFinal(modifiers),
                        "InjectLogger annotation is not supported on final fields");

                ReflectionUtils.makeAccessible(field);

                Logger logger = LoggerFactory.getLogger(clazz);

                ReflectionUtils.setField(field, bean, logger);
            }
        }
    });
}

From source file:com.anteam.demo.codec.common.CoderUtil.java

public static Object encode(Object source, EncryptAlgorithm encryptAlgorithm, byte[] key)
        throws EncoderException {
    if (source == null || encryptAlgorithm == null) {
        return null;
    }/*w w w  .  j ava2s .c  o  m*/
    Object result = source;
    if (source instanceof byte[]) {
        return CoderUtil.encode((byte[]) source, encryptAlgorithm, key);
    } else if (source instanceof String) {
        return CoderUtil.encode((String) source, encryptAlgorithm, key);
    }
    Field[] fields = source.getClass().getDeclaredFields();
    for (Field field : fields) {
        Encrypted encrypted = field.getAnnotation(Encrypted.class);
        if (encrypted != null) {
            ReflectionUtils.makeAccessible(field);
            if (!Modifier.isStatic(field.getModifiers())) {
                try {
                    field.set(source, CoderUtil.encode(field.get(source)));
                } catch (IllegalAccessException e) {
                    LOG.error("?:" + source.getClass().getName() + ":" + field.getName(), e);
                }
            }
        }
    }
    return result;
}

From source file:py.una.pol.karaku.test.test.ValidationMessagesTest.java

@Test
public void testConstants() {

    ReflectionUtils.doWithFields(ValidationMessages.class, new FieldCallback() {

        @Override// w ww  .j av a 2 s  .c om
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {

            String value = (String) field.get(null);
            assertNotNull(value);
            assertTrue("Key: " + value + " not found", keys.contains(value));
        }
    }, new FieldFilter() {

        @Override
        public boolean matches(Field field) {

            int modifiers = field.getModifiers();
            return Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)
                    && Modifier.isPublic(modifiers);
        }
    });
}

From source file:org.apache.camel.spring.util.MainRunner.java

public void runMethodWithoutCatchingExceptions()
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    if (delay > 0) {
        try {/*from  w w  w. j a  v a2  s.  c  om*/
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    Method method = main.getMethod("main", String[].class);
    if (!Modifier.isStatic(method.getModifiers())) {
        throw new IllegalArgumentException("The main method is not static!: " + method);
    }
    Object[] arguments = { getArgs() };
    method.invoke(null, arguments);
}

From source file:com.evolveum.midpoint.repo.sql.query.definition.ClassDefinitionParser.java

private void updateEntityDefinition(EntityDefinition entity) {
    LOGGER.trace("### {}", new Object[] { entity.getJpaName() });
    addVirtualDefinitions(entity);//from   ww  w  .j a v a 2  s  .  com
    Method[] methods = entity.getJpaType().getMethods();

    entity.setEmbedded(entity.getJpaType().getAnnotation(Embeddable.class) != null);

    for (Method method : methods) {
        String methodName = method.getName();
        if (Modifier.isStatic(method.getModifiers()) || "getClass".equals(methodName)
                || !methodName.startsWith("is") && !methodName.startsWith("get")) {
            //it's not getter for property
            continue;
        }

        if (method.isAnnotationPresent(Transient.class)) {
            continue;
        }

        LOGGER.trace("# {}", new Object[] { methodName });

        QName jaxbName = getJaxbName(method);
        Class jaxbType = getJaxbType(method);
        String jpaName = getJpaName(method);
        Definition definition = createDefinition(jaxbName, jaxbType, jpaName, method);
        entity.addDefinition(definition);
    }
}

From source file:net.redwarp.library.database.TableInfo.java

@SuppressWarnings("unchecked")
private TableInfo(Class<T> c) {
    mClass = c;//  w  w  w .ja  v a 2s.  co  m

    if (c.isAnnotationPresent(Version.class)) {
        final Version version = c.getAnnotation(Version.class);
        mVersion = version.value();
    } else {
        mVersion = 1;
    }

    Field[] fields = mClass.getDeclaredFields();
    //        mFieldMap = new HashMap<>(fields.length);
    mColumns = new HashMap<>(fields.length);
    mObjectFields = new ArrayList<>();

    List<String> columnNames = new ArrayList<>(fields.length);
    List<Field> finalFields = new ArrayList<>(fields.length);
    List<Field> chainDeleteFields = new ArrayList<>(fields.length);

    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            SQLiteUtils.SQLiteType type = SQLiteUtils.getSqlLiteTypeForField(field);
            if (type != null) {
                field.setAccessible(true);
                if (field.isAnnotationPresent(PrimaryKey.class)) {
                    if (primaryKey != null) {
                        throw new RuntimeException("There can be only one primary key");
                    }
                    final PrimaryKey primaryKeyAnnotation = field.getAnnotation(PrimaryKey.class);
                    String name = primaryKeyAnnotation.name();
                    if ("".equals(name)) {
                        name = getColumnName(field);
                    }
                    columnNames.add(name);
                    primaryKey = new Column(name, field, SQLiteUtils.SQLiteType.INTEGER);
                } else {
                    final String name = getColumnName(field);
                    columnNames.add(name);
                    mColumns.put(field, new Column(name, field, type));
                }

                finalFields.add(field);
            } else {
                // Not a basic field;
                if (field.isAnnotationPresent(Chain.class)) {
                    // We must serialize/unserialize this as well
                    final Chain chainAnnotation = field.getAnnotation(Chain.class);
                    if (chainAnnotation.delete()) {
                        chainDeleteFields.add(field);
                    }
                    final String name = getColumnName(field);
                    columnNames.add(name);
                    Column column = new Column(name, field, SQLiteUtils.SQLiteType.INTEGER);
                    mColumns.put(field, column);
                    mObjectFields.add(field);
                    finalFields.add(field);
                }
            }
        }
    }
    mColumnNames = columnNames.toArray(new String[columnNames.size()]);
    mFields = finalFields.toArray(new Field[finalFields.size()]);
    mChainDeleteFields = chainDeleteFields.toArray(new Field[chainDeleteFields.size()]);
}