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:com.crowsofwar.gorecore.config.ConfigLoader.java

/**
 * Tries to load the field of the {@link #obj object} with the correct
 * {@link #data}.//from   w ww  .j  a  v a  2  s.  c o m
 * <p>
 * If the field isn't marked with @Load, does nothing. Otherwise, will
 * attempt to set the field's value (with reflection) to the data set in the
 * map.
 * 
 * @param field
 *            The field to load
 */
private <T> void loadField(Field field) {

    Class<?> cls = field.getDeclaringClass();
    Class<?> fieldType = field.getType();
    if (fieldType.isPrimitive())
        fieldType = ClassUtils.primitiveToWrapper(fieldType);

    try {

        if (field.getAnnotation(Load.class) != null) {

            if (Modifier.isStatic(field.getModifiers())) {

                GoreCore.LOGGER.log(Level.WARN,
                        "[ConfigLoader] Warning: Not recommended to mark static fields with @Load, may work out weirdly.");
                GoreCore.LOGGER.log(Level.WARN,
                        "This field is " + field.getDeclaringClass().getName() + "#" + field.getName());
                GoreCore.LOGGER.log(Level.WARN, "Use a singleton instead!");

            }

            // Should load this field

            HasCustomLoader loaderAnnot = fieldType.getAnnotation(HasCustomLoader.class);
            CustomLoaderSettings loaderInfo = loaderAnnot == null ? new CustomLoaderSettings()
                    : new CustomLoaderSettings(loaderAnnot);

            Object fromData = data.get(field.getName());
            Object setTo;

            boolean tryDefaultValue = fromData == null || ignoreConfigFile;

            if (tryDefaultValue) {

                // Nothing present- try to load default value

                if (field.get(obj) != null) {

                    setTo = field.get(obj);

                } else {
                    throw new ConfigurationException.UserMistake(
                            "No configured definition for " + field.getName() + ", no default value");
                }

            } else {

                // Value present in configuration.
                // Use the present value from map: fromData

                Class<Object> from = (Class<Object>) fromData.getClass();
                Class<?> to = fieldType;

                setTo = convert(fromData, to, field.getName());

            }
            usedValues.put(field.getName(), setTo);

            // If not a java class, probably custom; needs to NOT have the
            // '!!' in front
            if (!setTo.getClass().getName().startsWith("java")) {
                representer.addClassTag(setTo.getClass(), Tag.MAP);
                classTags.add(setTo.getClass());
            }

            // Try to apply custom loader, if necessary

            try {

                if (loaderInfo.hasCustomLoader())
                    loaderInfo.customLoaderClass.newInstance().load(null, setTo);

            } catch (InstantiationException | IllegalAccessException e) {

                throw new ConfigurationException.ReflectionException(
                        "Couldn't create a loader class of loader " + loaderInfo.customLoaderClass.getName(),
                        e);

            } catch (Exception e) {

                throw new ConfigurationException.Unexpected(
                        "An unexpected error occurred while using a custom object loader from config. Offending loader is: "
                                + loaderInfo.customLoaderClass,
                        e);

            }

            if (loaderInfo.loadFields)
                field.set(obj, setTo);

        }

    } catch (ConfigurationException e) {

        throw e;

    } catch (Exception e) {

        throw new ConfigurationException.Unexpected("An unexpected error occurred while loading field \""
                + field.getName() + "\" in class \"" + cls.getName() + "\"", e);

    }

}

From source file:org.makersoft.activesql.builder.GenericStatementBuilder.java

public GenericStatementBuilder(Configuration configuration, Class<?> entityClass) {
    super(configuration);
    this.entityClass = entityClass;

    String resource = entityClass.getName().replace('.', '/') + ".java (best guess)";
    assistant = new MapperBuilderAssistant(configuration, resource);

    entity = entityClass.getAnnotation(Entity.class);
    mapperType = entity.mapper();/*  www.  java 2s.co  m*/

    if (!mapperType.isAssignableFrom(Void.class)) {
        namespace = mapperType.getName();
    } else {
        namespace = entityClass.getName();
    }

    assistant.setCurrentNamespace(namespace);

    databaseId = super.getConfiguration().getDatabaseId();
    lang = super.getConfiguration().getDefaultScriptingLanuageInstance();

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Table table = entityClass.getAnnotation(Table.class);
    if (table == null) {
        tableName = CaseFormatUtils.camelToUnderScore(entityClass.getSimpleName());
    } else {
        tableName = table.name();
    }

    ///~~~~~~~~~~~~~~~~~~~~~~
    idField = AnnotationUtils.findDeclaredFieldWithAnnoation(Id.class, entityClass);

    versionField = AnnotationUtils.findDeclaredFieldWithAnnoation(Version.class, entityClass);

    ReflectionUtils.doWithFields(entityClass, new FieldCallback() {

        @Override
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            columnFields.add(field);
        }
    }, new FieldFilter() {

        @Override
        public boolean matches(Field field) {
            if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
                return false;
            }

            for (Annotation annotation : field.getAnnotations()) {
                if (Transient.class.isAssignableFrom(annotation.getClass())
                        || Id.class.isAssignableFrom(annotation.getClass())) {
                    return false;
                }
            }

            return true;
        }
    });
}

From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java

/**
 * Build JSP function models from an annotated class
 * @param type class with annotated static methods
 * @return JSP function models//  w  ww  .j  a  v  a 2  s .  c om
 */
public Collection<JspFunctionModel> getFunctionMetadata(Class<?> type) {
    Collection<JspFunctionModel> functions = new ArrayList<JspFunctionModel>();
    for (Method method : type.getMethods()) {
        if (Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers())
                && method.isAnnotationPresent(JspFunction.class)) {
            JspFunction functionAnnotation = method.getAnnotation(JspFunction.class);
            JspFunctionModel metadata = new JspFunctionModel();
            metadata.name = functionAnnotation.name();
            metadata.functionClass = type.getName();
            JspFunctionSignature signature = new JspFunctionSignature();
            signature.name = method.getName();
            signature.argumentTypes = method.getParameterTypes();
            signature.returnType = method.getReturnType();
            metadata.signature = signature;
            functions.add(metadata);
        }
    }
    return functions;
}

From source file:com.diversityarrays.dal.db.DalDatabaseUtil.java

static public void addEntityFields(Class<? extends DalEntity> entityClass, DalResponseBuilder responseBuilder) {

    responseBuilder.addResponseMeta("SCol");

    for (Field fld : entityClass.getDeclaredFields()) {
        if (!Modifier.isStatic(fld.getModifiers())) {
            Column column = fld.getAnnotation(Column.class);
            if (column != null) {

                DalResponseBuilder builder = responseBuilder.startTag("SCol");

                builder.attribute("Required", column.nullable() ? "0" : "1");

                int colSize = 11;
                Class<?> fieldType = fld.getType();
                if (String.class == fieldType) {
                    colSize = column.length();
                }/* w w  w  . j a  v  a  2s. co  m*/
                builder.attribute("ColSize", Integer.toString(colSize));

                builder.attribute("Description", "");

                builder.attribute("Name", column.name());

                // TODO Synchronise with the Perl DAL code
                builder.attribute("DataType", fieldType.getSimpleName().toLowerCase());

                builder.endTag();
            }
        }
    }
}

From source file:com.github.geequery.codegen.ast.JavaUnit.java

/**
 * Equals//from ww  w . java  2 s  . com
 * @param idfields ?fields
 * @param overwirte ?
 * @param doSuperMethod ?
 * @return
 */
public boolean createEqualsMethod(List<JavaField> idfields, boolean overwirte, String doSuperMethod) {
    JavaMethod equals = new JavaMethod("equals");
    equals.setReturnType(boolean.class);
    equals.addparam(IClassUtil.of(Object.class), "rhs0", Modifier.FINAL);
    if (methods.containsKey(equals.getKey())) {//?
        if (!overwirte) {
            return false;
        }
    }
    equals.addContent("if (rhs0 == null)return false;");
    String simpleName = getSimpleName();
    equals.addContent(simpleName + " rhs=(" + simpleName + ")rhs0;");
    //
    for (int i = 0; i < idfields.size(); i++) {
        JavaField field = idfields.get(i);
        String name = field.getName();
        if (Modifier.isAbstract(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) {
            continue;
        }
        equals.addContent("if(!ObjectUtils.equals(" + name + ", rhs." + name + ")) return false;");
    }
    if (StringUtils.isEmpty(doSuperMethod)) {
        equals.addContent("return true;");
    } else {
        equals.addContent("return super." + doSuperMethod + "(rhs);");
    }
    addMethod(equals);
    addImport(ObjectUtils.class);
    return true;
}

From source file:org.apache.tajo.engine.function.FunctionLoader.java

private static boolean isPublicStaticMethod(Method method) {
    return Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers());
}

From source file:com.netflix.bdp.inviso.history.TraceJobHistoryLoader.java

private void handleJobEvent(HistoryEvent event) throws IllegalArgumentException, IllegalAccessException,
        NoSuchMethodException, InvocationTargetException {
    for (Field f : event.getDatum().getClass().getFields()) {
        f.setAccessible(true);// w  ww. j a v a 2s .c o  m

        if (Modifier.isStatic(f.getModifiers())) {
            continue;
        }

        String name = f.getName();
        Object value = f.get(event.getDatum());

        if (skipElements.contains(name)) {
            continue;
        }

        if (value instanceof CharSequence) {
            value = value.toString();
        }

        if (value == null || value.toString().trim().isEmpty()) {
            continue;
        }

        if (COUNTER_TAGS.containsKey(name)) {
            Method m = event.getClass().getDeclaredMethod(COUNTER_TAGS.get(name), new Class[0]);
            m.setAccessible(true);

            Counters counters = (Counters) m.invoke(event, new Object[0]);
            value = handleCounterEntries(counters);
        }

        job.put(name, value);
    }
}

From source file:de.taimos.dvalin.jaxrs.remote.RemoteServiceBeanPostProcessor.java

private InjectionMetadata buildResourceMetadata(Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {/* ww  w .  j  av a2  s.co m*/
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
        for (Field field : targetClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(RemoteService.class)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException(
                            "@RemoteService annotation is not supported on static fields");
                }
                currElements.add(new RemoteServiceElement(field, field, null));
            }
        }
        for (Method method : targetClass.getDeclaredMethods()) {
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                continue;
            }
            if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (bridgedMethod.isAnnotationPresent(RemoteService.class)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException(
                                "@RemoteService annotation is not supported on static methods");
                    }
                    if (method.getParameterTypes().length != 1) {
                        throw new IllegalStateException(
                                "@RemoteService annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new RemoteServiceElement(method, bridgedMethod, pd));
                }
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while ((targetClass != null) && (targetClass != Object.class));

    return new InjectionMetadata(clazz, elements);
}

From source file:de.taimos.dvalin.test.jaxrs.TestProxyBeanPostProcessor.java

private InjectionMetadata buildResourceMetadata(Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {/*  w  w w. ja v  a  2  s . c o m*/
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
        for (Field field : targetClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(TestProxy.class)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException("@TestProxy annotation is not supported on static fields");
                }
                currElements.add(new TestProxyElement(field, null));
            }
        }
        for (Method method : targetClass.getDeclaredMethods()) {
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                continue;
            }
            if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (bridgedMethod.isAnnotationPresent(TestProxy.class)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException(
                                "@TestProxy annotation is not supported on static methods");
                    }
                    if (method.getParameterTypes().length != 1) {
                        throw new IllegalStateException(
                                "@TestProxy annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new TestProxyElement(method, pd));
                }
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while ((targetClass != null) && (targetClass != Object.class));

    return new InjectionMetadata(clazz, elements);
}

From source file:com.shenit.commons.utils.GsonUtils.java

/**
 * ???./*from  www .  j  ava  2s. co  m*/
 * @param clazz
 * @return
 */
public static Field<?>[] serializeFields(Class<?> clazz) {
    if (REGISTERED_FIELDS.containsKey(clazz))
        return REGISTERED_FIELDS.get(clazz);
    java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
    List<Field<?>> fs = Lists.newArrayList();
    SerializedName serializedName;
    JsonProperty jsonProp;
    IgnoreField ignore;
    for (java.lang.reflect.Field field : fields) {
        if (field == null)
            continue;
        serializedName = field.getAnnotation(SerializedName.class);
        jsonProp = field.getAnnotation(JsonProperty.class);
        ignore = field.getAnnotation(IgnoreField.class);
        if (ignore != null)
            continue;
        String name = null;
        if (serializedName != null) {
            name = serializedName.value();
        } else if (jsonProp != null) {
            name = jsonProp.value();
        } else {
            name = Modifier.isStatic(field.getModifiers()) ? null : field.getName();
        }
        if (name == null)
            continue;

        Default defVal = field.getDeclaredAnnotation(Default.class);
        fs.add(new Field(name, field.getName(), field.getType(), defVal == null ? null : defVal.value()));
    }
    Field<?>[] fsArray = fs.toArray(new Field<?>[0]);
    REGISTERED_FIELDS.put(clazz, fsArray);
    return fsArray;
}