Example usage for java.lang.reflect Method getModifiers

List of usage examples for java.lang.reflect Method getModifiers

Introduction

In this page you can find the example usage for java.lang.reflect Method getModifiers.

Prototype

@Override
public int getModifiers() 

Source Link

Usage

From source file:org.callimachusproject.webdriver.helpers.BrowserFunctionalTestCase.java

@Override
public void runTest() throws Throwable {
    Method runMethod = null;
    try {/*from   w w  w.  j a va2 s.c  om*/
        runMethod = this.getClass().getMethod(getMethodName(), (Class[]) null);
    } catch (NoSuchMethodException e) {
        fail("Method \"" + getMethodName() + "\" not found");
    }
    if (!Modifier.isPublic(runMethod.getModifiers())) {
        fail("Method \"" + getMethodName() + "\" should be public");
    }

    try {
        runMethod.invoke(this, (Object[]) new Class[0]);
    } catch (InvocationTargetException e) {
        e.fillInStackTrace();
        throw e.getTargetException();
    } catch (IllegalAccessException e) {
        e.fillInStackTrace();
        throw e;
    }
}

From source file:jenkins.scm.api.SCMHeadMixinEqualityGenerator.java

/**
 * Creates the {@link SCMHeadMixin.Equality} instance.
 *
 * @param type the {@link SCMHead} type to create the instance for.
 * @return the {@link SCMHeadMixin.Equality} instance.
 *///www. ja  v a  2  s .  c  o  m
@NonNull
private SCMHeadMixin.Equality create(@NonNull Class<? extends SCMHead> type) {
    Map<String, Method> properties = new TreeMap<String, Method>();
    for (Class clazz : (List<Class>) ClassUtils.getAllInterfaces(type)) {
        if (!SCMHeadMixin.class.isAssignableFrom(clazz)) {
            // not a mix-in
            continue;
        }
        if (SCMHeadMixin.class == clazz) {
            // no need to check this by reflection
            continue;
        }
        if (!Modifier.isPublic(clazz.getModifiers())) {
            // not public
            continue;
        }
        // this is a mixin interface, only look at declared properties;
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.getReturnType() == Void.class) {
                // nothing to do with us
                continue;
            }
            if (!Modifier.isPublic(method.getModifiers())) {
                // should never get here
                continue;
            }
            if (Modifier.isStatic(method.getModifiers())) {
                // might get here with Java 8
                continue;
            }
            if (method.getParameterTypes().length != 0) {
                // not a property
                continue;
            }
            String name = method.getName();
            if (!name.matches("^((is[A-Z0-9_].*)|(get[A-Z0-9_].*))$")) {
                // not a property
                continue;
            }
            if (name.startsWith("is")) {
                name = "" + Character.toLowerCase(name.charAt(2))
                        + (name.length() > 3 ? name.substring(3) : "");
            } else {
                name = "" + Character.toLowerCase(name.charAt(3))
                        + (name.length() > 4 ? name.substring(4) : "");
            }
            if (properties.containsKey(name)) {
                // a higher priority interface already defined the method
                continue;
            }
            properties.put(name, method);
        }
    }
    if (properties.isEmpty()) {
        // no properties to consider
        return new ConstantEquality();
    }
    if (forceReflection) {
        return new ReflectiveEquality(properties.values().toArray(new Method[properties.size()]));
    }
    // now we define the class
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    String name = SCMHeadMixin.class.getPackage().getName() + ".internal." + type.getName();

    // TODO Move to 1.7 opcodes once baseline 1.612+
    cw.visit(Opcodes.V1_6, ACC_PUBLIC, name.replace('.', '/'), null, Type.getInternalName(Object.class),
            new String[] { Type.getInternalName(SCMHeadMixin.Equality.class) });
    generateDefaultConstructor(cw);
    generateEquals(cw, properties.values());
    byte[] image = cw.toByteArray();

    Class<? extends SCMHeadMixin.Equality> c = defineClass(name, image, 0, image.length)
            .asSubclass(SCMHeadMixin.Equality.class);

    try {
        return c.newInstance();
    } catch (InstantiationException e) {
        // fallback to reflection
    } catch (IllegalAccessException e) {
        // fallback to reflection
    }
    return new ReflectiveEquality(properties.values().toArray(new Method[properties.size()]));

}

From source file:com.tower.service.test.SoafwTesterMojo.java

/**
 * /*w  w  w .  j  a  va  2  s.c  o m*/
 * @param className
 *            
 */
private void appendTest(String className) {
    /**
     * ?? ?public
     * ?MojoExecutionException??????
     */
    try {

        Map<String, Integer> methodCnt = new HashMap<String, Integer>();
        boolean hasmethod = false;

        Map<String, String> methodDefs = new HashMap<String, String>();
        Class cls = cl.loadClass(className);// 
        Class[] inters = cls.getInterfaces();
        int len = 0;
        if (inters == null || (len = inters.length) == 0) {
            return;
        }
        for (int i = 0; i < len; i++) {

            Class interCls = inters[i];

            this.getLog().info("@interface: " + interCls.getName());

            String name = project.getName();

            Method[] methods = null;

            if (name.endsWith("-dao")) {
                methods = interCls.getDeclaredMethods();
            } else {
                methods = interCls.getMethods();
            }

            int mlen = 0;
            if (methods != null && (mlen = methods.length) > 0) {

                StringBuffer methodBuf = new StringBuffer();

                for (int m = 0; m < mlen; m++) {
                    Method method = methods[m];
                    int modf = method.getModifiers();
                    if (modf == 1025) {// ??
                        hasmethod = true;
                        /**
                         * ??????Test ???=??+Test
                         * ??:basedPath+File.separator
                         * +src+File.separator+test+File.separator
                         * +pkg+definesArray[i]+Test+.java
                         */
                        if (methodCnt.containsKey(method.getName())) {
                            methodCnt.put(method.getName(), methodCnt.get(method.getName()) + 1);
                        } else {
                            methodCnt.put(method.getName(), 0);
                        }
                        int cnt = methodCnt.get(method.getName());

                        addMethod(methodDefs, methodBuf, method, cnt);
                    }
                }
            }
        }

        Class tstCls = cl.loadClass(className + "Test");// 

        Method[] methods = tstCls.getDeclaredMethods();
        len = methods == null ? 0 : methods.length;
        this.getLog().info("" + tstCls.getSimpleName() + "?" + len);

        /**
         * ??public
         */
        for (int m = 0; m < len; m++) {

            Method method = methods[m];
            SoaFwTest test = method.getAnnotation(SoaFwTest.class);
            if (test == null) {
                this.getLog()
                        .info(tstCls.getSimpleName() + " method " + method.getName() + "SoaFwTest");
                continue;
            }

            String id = test.id();

            if (methodDefs.containsKey(id)) {
                methodDefs.remove(id);
            }
        }

        if ((len = methodDefs.size()) == 0) {
            return;
        }

        String[] methodImpls = new String[len];
        methodDefs.keySet().toArray(methodImpls);
        // TODO  ???

        StringBuilder src = new StringBuilder();

        String srcs = readTestSrc(className);

        int index = srcs.lastIndexOf("}");

        // this.getLog().info(srcs);
        //this.getLog().info("lastIndexOf(}):" + index);

        String impls = srcs.substring(0, index - 1);

        src.append(impls);

        src.append("\n");
        this.getLog().info("?: " + className + "Test");
        StringBuilder appends = new StringBuilder();
        this.getLog().info("?");
        for (int i = 0; i < len; i++) {
            String methodId = methodImpls[i];
            String method = methodDefs.get(methodId);
            appends.append(method);
            appends.append("\n");
        }

        src.append(appends.toString());

        src.append("}");

        Package pkg = tstCls.getPackage();
        String pkgName = pkg.getName();
        String pkgPath = pkgName.replace(".", File.separator);

        String testBaseSrcPath = basedPath + File.separator + "src" + File.separator + "test" + File.separator
                + "java";
        String testSrcFullPath = testBaseSrcPath + File.separator + pkgPath;

        write(testSrcFullPath, tstCls.getSimpleName() + ".java", src.toString());

    } catch (Exception e) {
        this.getLog().error(e);
    } catch (Error er) {
        this.getLog().error(er);
    }
}

From source file:org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.java

private boolean isPublic(Method method) {
    return Modifier.isPublic(method.getModifiers());
}

From source file:com.kjt.service.common.SoafwTesterMojo.java

/**
 * /*from   ww  w.j  a  va 2s .  c  o m*/
 * @param className 
 */
private void appendTest(String className) {
    /**
     * ?? ?public
     * ?MojoExecutionException??????
     */
    try {

        Map<String, Integer> methodCnt = new HashMap<String, Integer>();
        boolean hasmethod = false;

        Map<String, String> methodDefs = new HashMap<String, String>();
        Class cls = cl.loadClass(className);// 
        Class[] inters = cls.getInterfaces();
        int len = 0;
        if (inters == null || (len = inters.length) == 0) {
            return;
        }
        for (int i = 0; i < len; i++) {

            Class interCls = inters[i];

            this.getLog().info("@interface: " + interCls.getName());

            String name = project.getName();

            Method[] methods = null;

            if (name.endsWith("-dao")) {
                methods = interCls.getDeclaredMethods();
            } else {
                methods = interCls.getMethods();
            }

            int mlen = 0;
            if (methods != null && (mlen = methods.length) > 0) {

                StringBuffer methodBuf = new StringBuffer();

                for (int m = 0; m < mlen; m++) {
                    Method method = methods[m];
                    int modf = method.getModifiers();
                    if (modf == 1025) {// ??
                        hasmethod = true;
                        /**
                         * ??????Test ???=??+Test
                         * ??:basedPath+File.separator
                         * +src+File.separator+test+File.separator
                         * +pkg+definesArray[i]+Test+.java
                         */
                        if (methodCnt.containsKey(method.getName())) {
                            methodCnt.put(method.getName(), methodCnt.get(method.getName()) + 1);
                        } else {
                            methodCnt.put(method.getName(), 0);
                        }
                        int cnt = methodCnt.get(method.getName());

                        addMethod(methodDefs, methodBuf, method, cnt);
                    }
                }
            }
        }

        Class tstCls = cl.loadClass(className + "Test");// 

        Method[] methods = tstCls.getDeclaredMethods();
        len = methods == null ? 0 : methods.length;
        this.getLog().info("" + tstCls.getSimpleName() + "?" + len);

        /**
         * ??public
         */
        for (int m = 0; m < len; m++) {

            Method method = methods[m];
            SoaFwTest test = method.getAnnotation(SoaFwTest.class);
            if (test == null) {
                this.getLog()
                        .info(tstCls.getSimpleName() + " method " + method.getName() + "SoaFwTest");
                continue;
            }

            String id = test.id();

            if (methodDefs.containsKey(id)) {
                methodDefs.remove(id);
            }
        }

        if ((len = methodDefs.size()) == 0) {
            return;
        }

        String[] methodImpls = new String[len];
        methodDefs.keySet().toArray(methodImpls);
        // TODO  ???
        this.getLog().info("???");

        StringBuilder src = new StringBuilder();

        String srcs = readTestSrc(className);

        int index = srcs.lastIndexOf("}");

        this.getLog().info(srcs);
        this.getLog().info("lastIndexOf(}):" + index);
        String impls = srcs.substring(0, index - 1);

        src.append(impls);

        src.append("\n");

        StringBuilder appends = new StringBuilder();
        this.getLog().info("?");
        for (int i = 0; i < len; i++) {
            String methodId = methodImpls[i];
            String method = methodDefs.get(methodId);
            appends.append(method);
            appends.append("\n");
        }

        src.append(appends.toString());

        src.append("}");

        Package pkg = tstCls.getPackage();
        String pkgName = pkg.getName();
        String pkgPath = pkgName.replace(".", File.separator);

        String testBaseSrcPath = basedPath + File.separator + "src" + File.separator + "test" + File.separator
                + "java";
        String testSrcFullPath = testBaseSrcPath + File.separator + pkgPath;

        write(testSrcFullPath, tstCls.getSimpleName() + ".java", src.toString());

    } catch (Exception e) {
        this.getLog().error(e);
    } catch (Error er) {
        this.getLog().error(er);
    }
}

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

/**
 * Check if the method is abstract./*from   w w  w. j a  v a 2s  . co  m*/
 * 
 * @param method
 * @return
 */
public static boolean isAbstract(Method method) {
    return Modifier.isAbstract(method.getModifiers());
}

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.//from  w  w  w.ja  v a2  s.  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:org.castor.jaxb.reflection.ClassInfoBuilder.java

/**
 * Checks if the Method is describeable.
 * /* w  w  w  .  j  a  v  a 2  s  . c o  m*/
 * @param type
 *            the Class of the Method
 * @param method
 *            the Method to check
 * @return true if the method is describeable
 */
private boolean isDescribeable(final Class<?> type, final Method method) {
    boolean isDescribeable = true;
    Class<?> declaringClass = method.getDeclaringClass();
    if ((declaringClass != null) && !type.equals(declaringClass) && (!declaringClass.isInterface())) {
        isDescribeable = false;
    }
    if (method.isSynthetic()) {
        isDescribeable &= false;
    }
    if (Modifier.isStatic(method.getModifiers())) {
        isDescribeable &= false;
    }
    if (Modifier.isTransient(method.getModifiers())) {
        isDescribeable &= false;
    }
    if (!(javaNaming.isAddMethod(method) || javaNaming.isCreateMethod(method) || javaNaming.isGetMethod(method)
            || javaNaming.isIsMethod(method) || javaNaming.isSetMethod(method))) {
        isDescribeable = false;
    }
    return isDescribeable;
}

From source file:com.baidu.jprotobuf.pbrpc.spring.annotation.CommonAnnotationBeanPostProcessor.java

private InjectionMetadata findAnnotationMetadata(final Class clazz,
        final List<Class<? extends Annotation>> annotion) {
    // Quick check on the concurrent map first, with minimal locking.
    InjectionMetadata metadata = this.injectionMetadataCache.get(clazz);
    if (metadata == null) {
        synchronized (this.injectionMetadataCache) {
            metadata = this.injectionMetadataCache.get(clazz);
            if (metadata == null) {
                final InjectionMetadata newMetadata = new InjectionMetadata(clazz);
                ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() {
                    public void doWith(Field field) {
                        for (Class<? extends Annotation> anno : annotion) {
                            Annotation annotation = field.getAnnotation(anno);
                            if (annotation != null) {
                                if (Modifier.isStatic(field.getModifiers())) {
                                    throw new IllegalStateException(
                                            "Autowired annotation is not supported on static fields");
                                }/*from  w w w. j  a  v a2 s  .c  om*/
                                newMetadata.addInjectedField(new AutowiredFieldElement(field, annotation));
                            }

                        }
                    }
                });
                ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
                    public void doWith(Method method) {
                        for (Class<? extends Annotation> anno : annotion) {
                            Annotation annotation = method.getAnnotation(anno);
                            if (annotation != null
                                    && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                                if (Modifier.isStatic(method.getModifiers())) {
                                    throw new IllegalStateException(
                                            "Autowired annotation is not supported on static methods");
                                }
                                if (method.getParameterTypes().length == 0) {
                                    throw new IllegalStateException(
                                            "Autowired annotation requires at least one argument: " + method);
                                }
                                PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method);
                                newMetadata
                                        .addInjectedMethod(new AutowiredMethodElement(method, annotation, pd));
                            }

                        }
                    }
                });
                metadata = newMetadata;
                this.injectionMetadataCache.put(clazz, metadata);
            }
        }
    }
    return metadata;
}

From source file:de.xaniox.heavyspleef.core.flag.FlagRegistry.java

private Method[] getInitMethods(FlagClassHolder holder) {
    Class<? extends AbstractFlag<?>> clazz = holder.flagClass;
    List<Method> methods = Lists.newArrayList();

    for (Method method : clazz.getDeclaredMethods()) {
        if (!method.isAnnotationPresent(FlagInit.class)) {
            continue;
        }/*ww w . j a  v  a 2s  .  co m*/

        if ((method.getModifiers() & Modifier.STATIC) == 0) {
            continue;
        }

        method.setAccessible(true);
        methods.add(method);
    }

    return methods.toArray(new Method[methods.size()]);
}