集册 Java实例教程 获取一个方法并强制使其可访问,即使无法访问也是如此。

获取一个方法并强制使其可访问,即使无法访问也是如此。

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

605
获取一个方法并强制使其可访问,即使无法访问也是如此。

/*

 * $Id: ClassUtil.java 709153 2008-10-30 12:54:10Z apetrelli $

 *

 * Licensed to the Apache Software Foundation (ASF) under one

 * or more contributor license agreements.  See the NOTICE file

 * distributed with this work for additional information

 * regarding copyright ownership.  The ASF licenses this file

 * to you under the Apache License, Version 2.0 (the

 * "License"); you may not use this file except in compliance

 * with the License.  You may obtain a copy of the License at

 *

 * http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing,

 * software distributed under the License is distributed on an

 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY

 * KIND, either express or implied.  See the License for the

 * specific language governing permissions and limitations

 * under the License.

 */
 /*
 nowjava.com - 时  代  Java 提 供
 */

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;


public class Main{


    /**

     * Gets a method and forces it to be accessible, even if it is not.

     *

     * @param clazz The class from which the method will be got.

     * @param methodName The name of the method.

     * @param parameterTypes The parameter types that the method must match.

     * @return The method, if it is found.

     * @since 2.0.7

     */

    public static Method getForcedAccessibleMethod(Class<?> clazz,

            String methodName, Class<?>... parameterTypes) {

        Method method;

        try {

            method = clazz.getMethod(methodName, parameterTypes);

        } catch (SecurityException e) {

            throw new CannotAccessMethodException("Cannot access method '"

                    + methodName + "' in class '" + clazz.getName()

                    + "' for security reasons", e);

        } catch (NoSuchMethodException e) {

            throw new CannotAccessM
展开阅读全文