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

本文介绍了通过反射机制操纵类的私有函数,包括getDeclareMethod与getMethod的区别、setAccessible方法的作用以及具体实例演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值