Example usage for java.lang Class getDeclaredMethods

List of usage examples for java.lang Class getDeclaredMethods

Introduction

In this page you can find the example usage for java.lang Class getDeclaredMethods.

Prototype

@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Usage

From source file:de.taimos.dvalin.cloud.aws.AWSClientBeanPostProcessor.java

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

    do {//from w w  w . j  a v a 2  s.co  m
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<>();
        for (Field field : targetClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(AWSClient.class)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException("@AWSClient annotation is not supported on static fields");
                }
                currElements.add(new AWSClientElement(field, null, field.getAnnotation(AWSClient.class)));
            }
        }
        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(AWSClient.class)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException(
                                "@AWSClient annotation is not supported on static methods");
                    }
                    if (method.getParameterTypes().length != 1) {
                        throw new IllegalStateException(
                                "@AWSClient annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new AWSClientElement(method, pd, method.getAnnotation(AWSClient.class)));
                }
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while ((targetClass != null) && (targetClass != Object.class));

    return new InjectionMetadata(clazz, elements);
}

From source file:org.apache.felix.webconsole.AbstractWebConsolePlugin.java

/**
 * Returns a method which is called on the
 * {@link #getResourceProvider() resource provider} class to return an URL
 * to a resource which may be spooled when requested. The method has the
 * following signature://from w ww  .  ja va  2s. c  o m
 * <pre>
 * [modifier] URL getResource(String path);
 * </pre>
 * Where the <i>[modifier]</i> may be <code>public</code>, <code>protected</code>
 * or <code>private</code> (if the method is declared in the class of the
 * resource provider). It is suggested to use the <code>private</code>
 * modifier if the method is declared in the resource provider class or
 * the <code>protected</code> modifier if the method is declared in a
 * base class of the resource provider.
 *
 * @return The <code>getResource(String)</code> method or <code>null</code>
 *      if the {@link #getResourceProvider() resource provider} is
 *      <code>null</code> or does not provide such a method.
 */
private final Method getGetResourceMethod() {
    // return what we know of the getResourceMethod, if we already checked
    if (getResourceMethodChecked) {
        return getResourceMethod;
    }

    Method tmpGetResourceMethod = null;
    Object resourceProvider = getResourceProvider();
    if (resourceProvider != null) {
        try {
            Class cl = resourceProvider.getClass();
            while (tmpGetResourceMethod == null && cl != Object.class) {
                Method[] methods = cl.getDeclaredMethods();
                for (int i = 0; i < methods.length; i++) {
                    Method m = methods[i];
                    if (GET_RESOURCE_METHOD_NAME.equals(m.getName()) && m.getParameterTypes().length == 1
                            && m.getParameterTypes()[0] == String.class && m.getReturnType() == URL.class) {
                        // ensure modifier is protected or public or the private
                        // method is defined in the plugin class itself
                        int mod = m.getModifiers();
                        if (Modifier.isProtected(mod) || Modifier.isPublic(mod)
                                || (Modifier.isPrivate(mod) && cl == resourceProvider.getClass())) {
                            m.setAccessible(true);
                            tmpGetResourceMethod = m;
                            break;
                        }
                    }
                }
                cl = cl.getSuperclass();
            }
        } catch (Throwable t) {
            tmpGetResourceMethod = null;
        }
    }

    // set what we have found and prevent future lookups
    getResourceMethod = tmpGetResourceMethod;
    getResourceMethodChecked = true;

    // now also return the method
    return getResourceMethod;
}

From source file:ShowClass.java

/**
 * Display the modifiers, name, superclass and interfaces of a class or
 * interface. Then go and list all constructors, fields, and methods.
 *///from   ww  w .jav  a 2  s  .c om
public static void print_class(Class c) {
    // Print modifiers, type (class or interface), name and superclass.
    if (c.isInterface()) {
        // The modifiers will include the "interface" keyword here...
        System.out.print(Modifier.toString(c.getModifiers()) + " " + typename(c));
    } else if (c.getSuperclass() != null) {
        System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c) + " extends "
                + typename(c.getSuperclass()));
    } else {
        System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c));
    }

    // Print interfaces or super-interfaces of the class or interface.
    Class[] interfaces = c.getInterfaces();
    if ((interfaces != null) && (interfaces.length > 0)) {
        if (c.isInterface())
            System.out.print(" extends ");
        else
            System.out.print(" implements ");
        for (int i = 0; i < interfaces.length; i++) {
            if (i > 0)
                System.out.print(", ");
            System.out.print(typename(interfaces[i]));
        }
    }

    System.out.println(" {"); // Begin class member listing.

    // Now look up and display the members of the class.
    System.out.println("  // Constructors");
    Constructor[] constructors = c.getDeclaredConstructors();
    for (int i = 0; i < constructors.length; i++)
        // Display constructors.
        print_method_or_constructor(constructors[i]);

    System.out.println("  // Fields");
    Field[] fields = c.getDeclaredFields(); // Look up fields.
    for (int i = 0; i < fields.length; i++)
        // Display them.
        print_field(fields[i]);

    System.out.println("  // Methods");
    Method[] methods = c.getDeclaredMethods(); // Look up methods.
    for (int i = 0; i < methods.length; i++)
        // Display them.
        print_method_or_constructor(methods[i]);

    System.out.println("}"); // End class member listing.
}

From source file:com.google.dexmaker.ProxyBuilder.java

private void getMethodsToProxy(Set<MethodSetEntry> sink, Set<MethodSetEntry> seenFinalMethods, Class<?> c) {
    for (Method method : c.getDeclaredMethods()) {
        for (Class<? extends Annotation> annotation : Constants.annotation) {
            if (method.getAnnotation(annotation) != null) {
                MethodSetEntry entry = new MethodSetEntry(method);
                if (seenFinalMethods.contains(entry)) {
                    continue;
                }/*ww  w  .  j ava2  s. c  om*/
                if (sink.add(entry)) {
                    MethodEntity entity = new MethodEntity();
                    entity.clazz = c;
                    entity.name = method.getName();
                    entity.params = method.getParameterTypes();
                    entity.method = method;
                    methods.add(entity);
                }
            }
        }

        if (!Constants.method.contains(method.getName())) {
            // ??
            continue;
        }
        if ((method.getModifiers() & Modifier.FINAL) != 0) {
            // Skip final methods, we can't override them. We
            // also need to remember them, in case the same
            // method exists in a parent class.
            seenFinalMethods.add(new MethodSetEntry(method));
            continue;
        }

        if ((method.getModifiers() & STATIC) != 0) {
            // Skip static methods, overriding them has no effect.
            continue;
        }
        if ((method.getModifiers() & PRIVATE) != 0) {
            // Skip static methods, overriding them has no effect.
            continue;
        }
        //         if ((method.getModifiers() & Modifier.PROTECTED) != 0) {
        //            // Skip static methods, overriding them has no effect.
        //            continue;
        //         }
        if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) {
            // Skip finalize method, it's likely important that it execute as normal.
            continue;
        }
        MethodSetEntry entry = new MethodSetEntry(method);
        if (seenFinalMethods.contains(entry)) {
            // This method is final in a child class.
            // We can't override it.
            continue;
        }
        if (sink.add(entry)) {
            MethodEntity entity = new MethodEntity();
            entity.clazz = c;
            entity.name = method.getName();
            entity.params = method.getParameterTypes();
            entity.method = method;
            methods.add(entity);
        }
    }

    for (Class<?> i : c.getInterfaces()) {
        getMethodsToProxy(sink, seenFinalMethods, i);
    }
}

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

private void genTest(String basedPath, String className) {
    //  //from ww w .  jav a 2s .  c  om
    this.getLog().info("" + className + "");
    Map<String, Integer> methodCnt = new HashMap<String, Integer>();
    boolean hasmethod = false;
    try {

        Class cls = cl.loadClass(className);

        String testJFileName = cls.getSimpleName() + "Test.java";
        String pkgPath = cls.getPackage().getName().replace(".", File.separator);

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

        int len = 0;
        Class[] inters = cls.getInterfaces();
        if (inters == null || (len = inters.length) == 0) {
            return;
        }

        /**
         * package import
         */
        StringBuffer jHeadBuf = createTestJHeadByClass(cls);

        StringBuffer testJBuf = new StringBuffer();

        testJBuf.append(jHeadBuf);
        Map<String, String> methodDefs = new HashMap<String, String>();
        for (int j = 0; j < len; j++) {
            /**
             * ?
             */
            Class interCls = inters[j];

            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) {

                this.getLog().info("?" + className + "Test?");

                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);
                    }
                }

                testJBuf.append(methodBuf);
            } else {
                this.getLog().info(className + "");
            }
        }

        String testJFile = testJBuf.append("}").toString();
        if (hasmethod) {
            write(testJFilePath, testJFileName, testJFile);
        }

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

}

From source file:com.asuka.android.asukaandroid.view.ViewInjectorImpl.java

@SuppressWarnings("ConstantConditions")
private static void injectObject(Object handler, Class<?> handlerType, ViewFinder finder) {

    if (handlerType == null || IGNORED.contains(handlerType)) {
        return;/* w  w w  .j a v  a  2 s . co  m*/
    }

    // ?
    injectObject(handler, handlerType.getSuperclass(), finder);

    // inject view
    Field[] fields = handlerType.getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {

            Class<?> fieldType = field.getType();
            if (
            /* ??? */ Modifier.isStatic(field.getModifiers()) ||
            /* ?final */ Modifier.isFinal(field.getModifiers()) ||
            /* ? */ fieldType.isPrimitive() ||
            /* ? */ fieldType.isArray()) {
                continue;
            }

            ViewInject viewInject = field.getAnnotation(ViewInject.class);
            if (viewInject != null) {
                try {
                    View view = finder.findViewById(viewInject.value(), viewInject.parentId());
                    if (view != null) {
                        field.setAccessible(true);
                        field.set(handler, view);
                    } else {
                        throw new RuntimeException("Invalid @ViewInject for " + handlerType.getSimpleName()
                                + "." + field.getName());
                    }
                } catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
            }
        }
    } // end inject view

    // inject event
    Method[] methods = handlerType.getDeclaredMethods();
    if (methods != null && methods.length > 0) {
        for (Method method : methods) {

            if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPrivate(method.getModifiers())) {
                continue;
            }

            //??event
            Event event = method.getAnnotation(Event.class);
            if (event != null) {
                try {
                    // id?
                    int[] values = event.value();
                    int[] parentIds = event.parentId();
                    int parentIdsLen = parentIds == null ? 0 : parentIds.length;
                    //id?ViewInfo???
                    for (int i = 0; i < values.length; i++) {
                        int value = values[i];
                        if (value > 0) {
                            ViewInfo info = new ViewInfo();
                            info.value = value;
                            info.parentId = parentIdsLen > i ? parentIds[i] : 0;
                            method.setAccessible(true);
                            EventListenerManager.addEventMethod(finder, info, event, handler, method);
                        }
                    }
                } catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
            }
        }
    } // end inject event

}

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

/**
 * /*from   w  w 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  ???

        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:com.example.basedemo.view.ViewInjectorImpl.java

@SuppressWarnings("ConstantConditions")
private static void injectObject(Object handler, Class<?> handlerType, ViewFinder finder) {

    if (handlerType == null || IGNORED.contains(handlerType)) {
        return;//from   www.  ja  v a 2s . co m
    }

    // ?
    injectObject(handler, handlerType.getSuperclass(), finder);

    // inject view
    Field[] fields = handlerType.getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {

            Class<?> fieldType = field.getType();
            if (
            /* ??? */ Modifier.isStatic(field.getModifiers()) ||
            /* ?final */ Modifier.isFinal(field.getModifiers()) ||
            /* ? */ fieldType.isPrimitive() ||
            /* ? */ fieldType.isArray()) {
                continue;
            }

            ViewInject viewInject = field.getAnnotation(ViewInject.class);
            if (viewInject != null) {
                try {
                    View view = finder.findViewById(viewInject.value(), viewInject.parentId());
                    if (view != null) {
                        field.setAccessible(true);
                        field.set(handler, view);
                    } else {
                        throw new RuntimeException("Invalid @ViewInject for " + handlerType.getSimpleName()
                                + "." + field.getName());
                    }
                } catch (Throwable ex) {
                    Log.e(ex.getMessage(), ex.toString());
                }
            }
        }
    } // end inject view

    // inject event
    Method[] methods = handlerType.getDeclaredMethods();
    if (methods != null && methods.length > 0) {
        for (Method method : methods) {

            if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPrivate(method.getModifiers())) {
                continue;
            }

            //??event
            Event event = method.getAnnotation(Event.class);
            if (event != null) {
                try {
                    // id?
                    int[] values = event.value();
                    int[] parentIds = event.parentId();
                    int parentIdsLen = parentIds == null ? 0 : parentIds.length;
                    //id?ViewInfo???
                    for (int i = 0; i < values.length; i++) {
                        int value = values[i];
                        if (value > 0) {
                            ViewInfo info = new ViewInfo();
                            info.value = value;
                            info.parentId = parentIdsLen > i ? parentIds[i] : 0;
                            method.setAccessible(true);
                            EventListenerManager.addEventMethod(finder, info, event, handler, method);
                        }
                    }
                } catch (Throwable ex) {
                    Log.e(ex.getMessage(), ex.toString());
                }
            }
        }
    } // end inject event

}

From source file:gov.nih.nci.system.web.struts.action.RestQuery.java

protected boolean supportDeleteLink(String className) {
    if (isoEnabled)
        return false;

    String cName = className.substring(className.lastIndexOf(".") + 1, className.length());
    try {/*  w ww .j  a va2  s.  c  o  m*/
        Class klass = Class.forName(className + "Resource");

        Method[] allMethods = klass.getDeclaredMethods();
        String addName = "delete" + cName;
        for (Method m : allMethods) {
            String mname = m.getName();
            if (addName.equals(mname))
                return true;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:gov.nih.nci.system.web.struts.action.RestQuery.java

protected boolean supportUpdateLink(String className) {
    if (isoEnabled)
        return false;

    String cName = className.substring(className.lastIndexOf(".") + 1, className.length());
    try {//from w  w w  .  ja  v a2s. c  om
        Class klass = Class.forName(className + "Resource");

        Method[] allMethods = klass.getDeclaredMethods();
        String addName = "update" + cName;
        for (Method m : allMethods) {
            String mname = m.getName();
            if (addName.equals(mname))
                return true;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}