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.judoscript.jamaica.parser.JamaicaDumpVisitor.java

static void printAccessFlags(int flags) {
    if (Modifier.isPublic(flags))
        out.print("public ");
    else if (Modifier.isProtected(flags))
        out.print("protected ");
    else if (Modifier.isPrivate(flags))
        out.print("private ");

    if (Modifier.isAbstract(flags))
        out.print("abstract ");
    if (Modifier.isFinal(flags))
        out.print("final ");
    if (Modifier.isNative(flags))
        out.print("native ");
    if (Modifier.isStatic(flags))
        out.print("static ");
    if (Modifier.isStrict(flags))
        out.print("strict ");
    if (Modifier.isSynchronized(flags))
        out.print("synchronized ");
    if (Modifier.isTransient(flags))
        out.print("transient ");
    if (Modifier.isVolatile(flags))
        out.print("volative ");
}

From source file:net.abhinavsarkar.spelhelper.SpelHelper.java

private static List<Method> filterFunctions(final Class<?> clazz) {
    List<Method> allowedMethods = new ArrayList<Method>();
    for (Method method : clazz.getMethods()) {
        int modifiers = method.getModifiers();
        if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)
                && !method.getReturnType().equals(Void.TYPE)) {
            allowedMethods.add(method);//from www.j  ava  2  s. c  o m
        }
    }
    return allowedMethods;
}

From source file:io.github.benas.jpopulator.impl.PopulatorImpl.java

private boolean isStatic(Field field) {
    int fieldModifiers = field.getModifiers();
    return Modifier.isStatic(fieldModifiers);
}

From source file:adalid.core.XS1.java

static Collection<Field> getFields(Class<?> clazz, Class<?> top) throws SecurityException {
    ArrayList<Field> fields = new ArrayList<>();
    if (clazz == null || top == null) {
        return fields;
    }/*w  w w. j a  v a 2  s .  c o  m*/
    int modifiers;
    boolean restricted;
    Class<?> superClazz = clazz.getSuperclass();
    if (superClazz == null) {
        logger.trace(clazz.getName());
    } else {
        logger.trace(clazz.getName() + " extends " + superClazz.getName());
        if (top.isAssignableFrom(superClazz)) {
            //              fields.addAll(getFields(superClazz, top));
            Collection<Field> superFields = getFields(superClazz, top);
            for (Field field : superFields) {
                modifiers = field.getModifiers();
                restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
                if (restricted) {
                    continue;
                }
                fields.add(field);
            }
        }
    }
    if (top.isAssignableFrom(clazz)) {
        logger.trace("adding fields declared at " + clazz.getName());
        //          fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            modifiers = field.getModifiers();
            restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
            if (restricted) {
                continue;
            }
            fields.add(field);
        }
    }
    return getRidOfDupFields(fields);
}

From source file:org.apache.ignite.spi.deployment.uri.GridUriDeploymentFileProcessor.java

/**
 * Check that class may be instantiated as {@link org.apache.ignite.compute.ComputeTask} and used
 * in deployment./*from w ww  .  j  a v a2 s .  co  m*/
 *
 * Loaded task class must implement interface {@link org.apache.ignite.compute.ComputeTask}.
 * Only non-abstract, non-interfaces and public classes allowed.
 * Inner static classes also allowed for loading.
 *
 * @param cls Class to check
 * @return {@code true} if class allowed for deployment.
 */
private static boolean isAllowedTaskClass(Class<?> cls) {
    if (!ComputeTask.class.isAssignableFrom(cls))
        return false;

    int modifiers = cls.getModifiers();

    return !Modifier.isAbstract(modifiers) && !Modifier.isInterface(modifiers)
            && (!cls.isMemberClass() || Modifier.isStatic(modifiers)) && Modifier.isPublic(modifiers);
}

From source file:lucee.transformer.bytecode.reflection.ASMProxyFactory.java

private static byte[] _createMethod(Type type, Class clazz, Method method, Resource classRoot, String className)
        throws IOException {
    Class<?> rtn = method.getReturnType();
    Type rtnType = Type.getType(rtn);

    className = className.replace('.', File.separatorChar);
    ClassWriter cw = ASMUtil.getClassWriter();
    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, className, null, ASM_METHOD.getInternalName(), null);

    // CONSTRUCTOR

    GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, CONSTRUCTOR, null, null, cw);

    Label begin = new Label();
    adapter.visitLabel(begin);// w ww . jav a 2s .c o m
    adapter.loadThis();

    adapter.visitVarInsn(Opcodes.ALOAD, 1);
    adapter.visitVarInsn(Opcodes.ALOAD, 2);

    adapter.invokeConstructor(ASM_METHOD, CONSTRUCTOR);
    adapter.visitInsn(Opcodes.RETURN);

    Label end = new Label();
    adapter.visitLabel(end);

    adapter.endMethod();

    /*
             
        GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC,CONSTRUCTOR,null,null,cw);
                
        Label begin = new Label();
         adapter.visitLabel(begin);
       adapter.loadThis();
                 
        // clazz
         adapter.visitVarInsn(Opcodes.ALOAD, 2);
                 
         // parameterTypes 
         Class<?>[] params = method.getParameterTypes();
         Type[] paramTypes = new Type[params.length];
        ArrayVisitor av=new ArrayVisitor();
        av.visitBegin(adapter, Types.CLASS, params.length);
        for(int i=0;i<params.length;i++){
           paramTypes[i]=Type.getType(params[i]);
           av.visitBeginItem(adapter, i);
     loadClass(adapter,params[i]);
           av.visitEndItem(adapter);
        }
        av.visitEnd();
                
       adapter.invokeConstructor(ASM_METHOD, ASM_METHOD_CONSTRUCTOR);
       adapter.visitInsn(Opcodes.RETURN);
               
       Label end = new Label();
       adapter.visitLabel(end);
               
       adapter.endMethod();
     */

    // METHOD getName();
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, GET_NAME, null, null, cw);
    adapter.push(method.getName());
    adapter.visitInsn(Opcodes.ARETURN);
    adapter.endMethod();

    // METHOD getModifiers();
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, GET_MODIFIERS, null, null, cw);
    adapter.push(method.getModifiers());
    adapter.visitInsn(Opcodes.IRETURN);
    adapter.endMethod();

    // METHOD getReturnType();
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, GET_RETURN_TYPE_AS_STRING, null, null, cw);

    adapter.push(method.getReturnType().getName());
    adapter.visitInsn(Opcodes.ARETURN);

    adapter.endMethod();

    // METHOD INVOKE
    boolean isStatic = Modifier.isStatic(method.getModifiers());
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, INVOKE, null, null, cw);
    Label start = adapter.newLabel();
    adapter.visitLabel(start);

    // load Object
    if (!isStatic) {
        adapter.visitVarInsn(Opcodes.ALOAD, 1);
        adapter.checkCast(type);
    }

    // load params
    Class<?>[] params = method.getParameterTypes();

    Type[] paramTypes = new Type[params.length];
    for (int i = 0; i < params.length; i++) {
        paramTypes[i] = Type.getType(params[i]);
    }

    for (int i = 0; i < params.length; i++) {
        adapter.visitVarInsn(Opcodes.ALOAD, 2);
        adapter.push(i);
        //adapter.visitInsn(Opcodes.ICONST_0);
        adapter.visitInsn(Opcodes.AALOAD);

        adapter.checkCast(toReferenceType(params[i], paramTypes[i]));

        // cast
        if (params[i] == boolean.class)
            adapter.invokeVirtual(Types.BOOLEAN, BOOL_VALUE);
        else if (params[i] == short.class)
            adapter.invokeVirtual(Types.SHORT, SHORT_VALUE);
        else if (params[i] == int.class)
            adapter.invokeVirtual(Types.INTEGER, INT_VALUE);
        else if (params[i] == float.class)
            adapter.invokeVirtual(Types.FLOAT, FLT_VALUE);
        else if (params[i] == long.class)
            adapter.invokeVirtual(Types.LONG, LONG_VALUE);
        else if (params[i] == double.class)
            adapter.invokeVirtual(Types.DOUBLE, DBL_VALUE);
        else if (params[i] == char.class)
            adapter.invokeVirtual(Types.CHARACTER, CHR_VALUE);
        else if (params[i] == byte.class)
            adapter.invokeVirtual(Types.BYTE, BYT_VALUE);
        //else adapter.checkCast(paramTypes[i]);

    }

    // call method
    final org.objectweb.asm.commons.Method m = new org.objectweb.asm.commons.Method(method.getName(), rtnType,
            paramTypes);
    if (isStatic)
        adapter.invokeStatic(type, m);
    else
        adapter.invokeVirtual(type, m);

    // return
    if (rtn == void.class)
        ASMConstants.NULL(adapter);

    // cast result to object
    if (rtn == boolean.class)
        adapter.invokeStatic(Types.BOOLEAN, BOOL_VALUE_OF);
    else if (rtn == short.class)
        adapter.invokeStatic(Types.SHORT, SHORT_VALUE_OF);
    else if (rtn == int.class)
        adapter.invokeStatic(Types.INTEGER, INT_VALUE_OF);
    else if (rtn == long.class)
        adapter.invokeStatic(Types.LONG, LONG_VALUE_OF);
    else if (rtn == float.class)
        adapter.invokeStatic(Types.FLOAT, FLT_VALUE_OF);
    else if (rtn == double.class)
        adapter.invokeStatic(Types.DOUBLE, DBL_VALUE_OF);
    else if (rtn == char.class)
        adapter.invokeStatic(Types.CHARACTER, CHR_VALUE_OF);
    else if (rtn == byte.class)
        adapter.invokeStatic(Types.BYTE, BYT_VALUE_OF);

    adapter.visitInsn(Opcodes.ARETURN);

    adapter.endMethod();

    if (classRoot != null) {
        Resource classFile = classRoot.getRealResource(className + ".class");
        return store(cw.toByteArray(), classFile);
    }
    return cw.toByteArray();
}

From source file:com.github.mbenson.privileged.weaver.PrivilegedMethodWeaver.java

private boolean weave(CtClass type, CtMethod method)
        throws ClassNotFoundException, CannotCompileException, NotFoundException, IOException {
    final AccessLevel accessLevel = AccessLevel.of(method.getModifiers());
    if (!permitMethodWeaving(accessLevel)) {
        warn("Ignoring %s method %s.%s", accessLevel, type.getName(), toString(method));
        return false;
    }/*from  ww w .jav  a2s .c o  m*/
    if (AccessLevel.PACKAGE.compareTo(accessLevel) > 0) {
        warn("Possible security leak: granting privileges to %s method %s.%s", accessLevel, type.getName(),
                toString(method));
    }
    final String implName = generateName(method.getName());

    final CtMethod impl = CtNewMethod.copy(method, implName, type, null);
    impl.setModifiers(AccessLevel.PRIVATE.merge(method.getModifiers()));
    type.addMethod(impl);
    debug("Copied %2$s %1$s.%3$s to %4$s %1$s.%5$s", type.getName(), accessLevel, toString(method),
            AccessLevel.PRIVATE, toString(impl));

    final Body body = new Body();
    if (policy.isConditional()) {
        body.startBlock("if (%s)", policy.condition);
    }

    final boolean exc = method.getExceptionTypes().length > 0;

    if (exc) {
        body.startBlock("try");
    }

    final Class<?> iface = exc ? PrivilegedExceptionAction.class : PrivilegedAction.class;
    final CtClass actionType = createAction(type, impl, iface);
    final String action = generateName("action");

    body.append("final %s %s = new %s(", iface.getName(), action, actionType.getName());
    boolean firstParam;
    if (Modifier.isStatic(impl.getModifiers())) {
        firstParam = true;
    } else {
        body.append("$0");
        firstParam = false;
    }
    for (int i = 1, sz = impl.getParameterTypes().length; i <= sz; i++) {
        if (firstParam) {
            firstParam = false;
        } else {
            body.append(", ");
        }
        body.append('$').append(Integer.toString(i));
    }
    body.appendLine(");");

    final CtClass rt = method.getReturnType();
    final boolean isVoid = rt.equals(CtClass.voidType);

    final String doPrivileged = String.format("%1$s.doPrivileged(%2$s)", AccessController.class.getName(),
            action);
    if (isVoid) {
        body.append(doPrivileged).append(';').appendNewLine();
        if (policy.isConditional()) {
            body.appendLine("return;");
        }
    } else {
        final String cast = rt.isPrimitive() ? ((CtPrimitiveType) rt).getWrapperName() : rt.getName();
        // don't worry about wrapper NPEs because we should be simply
        // passing back an autoboxed value, then unboxing again
        final String result = generateName("result");
        body.appendLine("final %1$s %3$s = (%1$s) %2$s;", cast, doPrivileged, result);
        body.append("return %s", result);
        if (rt.isPrimitive()) {
            body.append(".%sValue()", rt.getName());
        }
        body.append(';').appendNewLine();
    }

    if (exc) {
        body.endBlock();
        final String e = generateName("e");
        body.startBlock("catch (%1$s %2$s)", PrivilegedActionException.class.getName(), e).appendNewLine();

        final String wrapped = generateName("wrapped");

        body.appendLine("final Exception %1$s = %2$s.getCause();", wrapped, e);
        for (final CtClass thrown : method.getExceptionTypes()) {
            body.startBlock("if (%1$s instanceof %2$s)", wrapped, thrown.getName());
            body.appendLine("throw (%2$s) %1$s;", wrapped, thrown.getName());
            body.endBlock();
        }
        body.appendLine(
                "throw %1$s instanceof RuntimeException ? (RuntimeException) %1$s : new RuntimeException(%1$s);",
                wrapped);
        body.endBlock();
    }

    if (policy.isConditional()) {
        // close if block we opened before:
        body.endBlock();
        // no security manager=> just call impl:
        if (!isVoid) {
            body.append("return ");
        }
        body.appendLine("%s($$);", impl.getName());
    }

    final String block = body.complete().toString();
    debug("Setting body of %s to:\n%s", toString(method), block);
    method.setBody(block);
    return true;
}

From source file:com.taobao.adfs.util.Utilities.java

public static String toStringByFields(Object object, boolean allFields) {
    if (object == null)
        return "null";
    StringBuilder stringBuilder = new StringBuilder(256);
    stringBuilder.append(object.getClass().getSimpleName()).append('[');
    Field[] fields = allFields ? ClassCache.getAllFields(object.getClass())
            : ClassCache.getDeclaredFields(object.getClass());
    for (int i = 0; i < fields.length; ++i) {
        if (fields[i].getAnnotation(IgnoreToString.class) != null)
            continue;
        fields[i].setAccessible(true);/*from w w  w  .  jav a  2s  .  c o  m*/
        if (Modifier.isStatic(fields[i].getModifiers()))
            continue;
        stringBuilder.append(fields[i].getName()).append('=');
        try {
            Object fieldValue = fields[i].get(object);
            if (fieldValue == null)
                fieldValue = "null";
            else {
                String timeFormat = getTimeFormatFromField(fields[i]);
                if (timeFormat != null)
                    fieldValue = longTimeToStringTime((Long) fieldValue, timeFormat);
            }
            stringBuilder.append(deepToString(fieldValue));
        } catch (Throwable t) {
            stringBuilder.append("unknown");
            logWarn(logger, "fail to get string for ", fields[i].getName(), t);
        }
        if (i < fields.length - 1)
            stringBuilder.append(',');
    }
    stringBuilder.append(']');
    return stringBuilder.toString();
}

From source file:org.apache.hadoop.fs.TestHarFileSystem.java

@Test
public void testInheritedMethodsImplemented() throws Exception {
    int errors = 0;
    for (Method m : FileSystem.class.getDeclaredMethods()) {
        if (Modifier.isStatic(m.getModifiers()) || Modifier.isPrivate(m.getModifiers())
                || Modifier.isFinal(m.getModifiers())) {
            continue;
        }/*from  w  ww .j  a  v a 2  s  . c om*/

        try {
            MustNotImplement.class.getMethod(m.getName(), m.getParameterTypes());
            try {
                HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
                LOG.error("HarFileSystem MUST not implement " + m);
                errors++;
            } catch (NoSuchMethodException ex) {
                // Expected
            }
        } catch (NoSuchMethodException exc) {
            try {
                HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
            } catch (NoSuchMethodException exc2) {
                LOG.error("HarFileSystem MUST implement " + m);
                errors++;
            }
        }
    }
    assertTrue((errors + " methods were not overridden correctly - see log"), errors <= 0);
}

From source file:com.wingnest.play2.origami.plugin.OrigamiPlugin.java

@SuppressWarnings("unchecked")
private void maintainProperties(final OClass oClass, final Class<?> javaClass) {
    final Map<String, Map<String, Object>> compositeIndexMap = new HashMap<String, Map<String, Object>>();
    final Map<String, OIndex<?>> classIndexCache = new HashMap<String, OIndex<?>>();
    final Map<String, OIndex<?>> compositeIndexCache = new HashMap<String, OIndex<?>>();
    final Set<String> wkCurIndexNames = new HashSet<String>();
    //      for ( final OProperty prop : oClass.properties() ) {
    //         debug("[b] prop name =%s, type = %s", prop.getName(), prop.getType());
    //      }//  ww  w.  ja va  2  s  . c o m
    for (final OIndex<?> index : oClass.getClassIndexes()) {
        wkCurIndexNames.add(index.getName());
        if (index.getName().indexOf('.') > -1) {
            classIndexCache.put(index.getName(), index);
        } else {
            compositeIndexCache.put(index.getName(), index);
        }
        //         debug("[b] index name =%s, type = %s", index.getName(), index.getType());
    }
    for (final Field field : javaClass.getDeclaredFields()) {
        if (Modifier.isStatic(field.getModifiers()) || field.isAnnotationPresent(Id.class)
                || field.isAnnotationPresent(Version.class) || field.isAnnotationPresent(Transient.class)
                || field.isAnnotationPresent(DisupdateFlag.class))
            continue;

        OProperty prop = oClass.getProperty(field.getName());
        final OType type = guessType(field);
        if (prop == null) {
            if (type != null) {
                debug("create property : %s", field.getName());
                prop = oClass.createProperty(field.getName(), type);
            }
        } else {
            if (!type.equals(prop.getType())) {
                deleteIndex(oClass, oClass.getName() + "." + field.getName(), classIndexCache,
                        compositeIndexCache);
                debug("drop property : %s", field.getName());
                oClass.dropProperty(field.getName());
                debug("create property : %s", field.getName());
                prop = oClass.createProperty(field.getName(), type);
            }
        }
        final Index index = field.getAnnotation(Index.class);
        if (index != null) {
            final String indexName = makeIndexName(javaClass, field);
            OIndex<?> oindex = classIndexCache.get(indexName);
            if (oindex == null) {
                debug("create Class Index : %s.%s", javaClass.getSimpleName(), field.getName());
                if (prop != null) {
                    oindex = oClass.createIndex(indexName, index.indexType(), field.getName());
                } else {
                    error("could not create Class Index : property(%s.%s) has't type", javaClass.getName(),
                            field.getName());
                }
            }
            if (oindex != null) {
                wkCurIndexNames.remove(oindex.getName());
            }
        }
        final CompositeIndex cindex = field.getAnnotation(CompositeIndex.class);
        if (cindex != null) {
            final String indexName = javaClass.getSimpleName() + "_" + cindex.indexName();
            Map<String, Object> ci = compositeIndexMap.get(indexName);
            if (ci == null) {
                ci = new HashMap<String, Object>();
                ci.put("fields", new HashSet<Field>());
                ci.put("indexType", OClass.INDEX_TYPE.UNIQUE);
            }
            if (!cindex.indexType().equals(OClass.INDEX_TYPE.UNIQUE))
                ci.put("indexType", cindex.indexType());
            ((Set<Field>) ci.get("fields")).add(field);
            compositeIndexMap.put(indexName, ci);
        }
    }

    for (final String cindexName : compositeIndexMap.keySet()) {
        final Map<String, Object> ci = compositeIndexMap.get(cindexName);
        final Set<Field> fields = (Set<Field>) ci.get("fields");
        final String[] fieldNames = new String[fields.size()];
        int i = 0;
        for (final Field f : fields) {
            fieldNames[i++] = f.getName();
        }
        final OIndex<?> oindex = compositeIndexCache.get(cindexName);
        if (oindex != null && !CollectionUtils.isEqualCollection(Arrays.asList(fieldNames),
                oindex.getDefinition().getFields())) {
            debug("recreate composite index : %s", cindexName);
            deleteIndex(oClass, cindexName, classIndexCache, compositeIndexCache);
        } else if (oindex == null) {
            debug("create composite index : %s", cindexName);
        }
        oClass.createIndex(cindexName, (OClass.INDEX_TYPE) ci.get("indexType"), fieldNames);
        wkCurIndexNames.remove(cindexName);
    }

    for (final String indexName : wkCurIndexNames) {
        final int ind = indexName.indexOf('.');
        if (ind > -1) {
            debug("delete index : %s", indexName);
        } else {
            debug("delete composite index : %s", indexName);
        }
        deleteIndex(oClass, indexName, classIndexCache, compositeIndexCache);
    }

    //      for ( final OProperty prop : oClass.properties() ) {
    //         debug("[a] prop name =%s, type = %s", prop.getName(), prop.getType());
    //      }
    //      for ( final OIndex<?> index : oClass.getClassIndexes() ) {
    //         debug("[a] class index name =%s, type = %s", index.getName(), index.getType());
    //      }
}