Get the methods declared as public within the class - Java Reflection

Java examples for Reflection:Method

Description

Get the methods declared as public within the class

Demo Code

/*******************************************************************************
 * Copyright (c) 2011 MadRobot.// www . ja  va 2s  . com
 * 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.java2s;
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 {
    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.
        for (int i = 0; i < result.length; i++) {
            Method method = result[i];
            int mods = method.getModifiers();
            if (!Modifier.isPublic(mods)) {
                result[i] = null;
            }
        }
        // Add it to the cache.
        declaredMethodCache.put(fclz, new SoftReference(result));
        return result;
    }
}

Related Tutorials