JavaSE 反射(进阶) 反射操纵private函数

来源:互联网 发布:南风知我意琰阙txt下载 编辑:程序博客网 时间:2024/05/23 19:44

一.getDeclareMethod 不同于getMethod 方法,后者只能操纵public函数,而前者凡是declare声明过的函数都能被操纵。


二.

public void setAccessible(boolean flag) throws SecurityException 方法解释:

该方法为Method Constructor Field类的父类AccessibleObject定义的方法。

引入JDK的原话:(Quote from JDK)

Set the accessible flag for this object to the indicated boolean value.
A value of true indicates that the reflected object should suppressJava language access checking when it is used.

设置object.setAccessible(true)意味着压制java的访问规则。

A value of false indicates that the reflected object should enforce Java language access checks. 

设置object.setAccessible(false)意味着强制执行java的访问规则。 


三. 下面为一个具体实例,展示如何用反射reflection机制来 操纵一个类的private函数:


package com.java.reflection;public class PrivateReflect {private String feedback(String str)  //等待被操纵的private函数{return "Hello "+str;}}

package com.java.reflection;import java.lang.reflect.Method;public class PrivateTest {public static void main(String[] args) throws Exception {Class<?> classType=PrivateReflect.class;Object p=classType.newInstance();Method method=classType.getDeclaredMethod("feedback",String.class);//Set the accessible flag for this object to the indicated boolean value.//A value of true indicates that the reflected object should suppress Java language access checking when it is used. //A value of false indicates that the reflected object should enforce Java language access checks.                 method.setAccessible(true);String str=(String)method.invoke(p,"Ma Yun");System.out.println(str);}}
输出:

Hello Ma Yun

0 0