集册 Java实例教程 获取在类中声明为public的方法

获取在类中声明为public的方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

583
获取在类中声明为public的方法

/*******************************************************************************

 * Copyright (c) 2011 MadRobot.

 * All rights reserved. This program and the accompanying materials

 * are made available under the terms of the GNU Lesser Public License v2.1

 * which accompanies this distribution, and is available at

 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html

 * 

 * Contributors:

 *  Elton Kent - initial API and implementation

 ******************************************************************************/

//package com.nowjava;//来 自 N o w  J a v a  .   c o m

import java.lang.ref.Reference;

import java.lang.ref.SoftReference;


import java.lang.reflect.Method;

import java.lang.reflect.Modifier;

import java.security.AccessController;

import java.security.PrivilegedAction;

import java.util.Collections;

import java.util.Map;

import java.util.WeakHashMap;


public class Main {// from n o w  j a v a  . c o m

    private static Map declaredMethodCache = Collections

            .synchronizedMap(new WeakHashMap());


    /**

     * Get the methods declared as public within the class

     * 

     * @param clz

     *            class to find public methods

     * @return

     */

    public static synchronized Method[] getPublicDeclaredMethods(Class clz) {

        // Looking up Class.getDeclaredMethods is relatively expensive,

        // so we cache the results.

        Method[] result = null;

        // if(!ReflectUtil.isPackageAccessible(clz)){

        // return new Method[0];

        // }

        final Class fclz = clz;

        Reference ref = (Reference) declaredMethodCache.get(fclz);

        if (ref != null) {

            result = (Method[]) ref.get();

            if (result != null) {

                return result;

            }

        }


        // We have to raise privilege for getDeclaredMethods

        result = (Method[]) AccessController

                .doPrivileged(new PrivilegedAction() {


                    public Object run() {

                        return fclz.getDeclaredMethods();

                    }

                });


        // Null out any non-public methods.

      
展开阅读全文