java访问私有方法

Java中对方法的定义存在四种修饰符,分别是public、protected、default、private,作用域分别如下:

 publicprotectedprotectedprivate
同一个类truetruetruetrue
同一个包truetruetruefalse
不同包子类truetruefalsefalse
不同包非子类truefalsefalsefalse

那么,当我们想访问不同类中的私有方法时该怎么做呢?

我们可以使用java的反射机制(reflection)

首先我们有这么一个类,只用于返回匹配到的姓名,和一个输出方法

package com.travelsky.pss.bkg.asom.canceltest.matchsegmentinfotest;


public class Reflections {
	
	private void sout() {
		System.out.println("reflection");
	}

	private String matchTravellerName(String name, String traveller) {
		String travellerName = name+traveller;
		
		return travellerName;
	}
}

但是这两个方法都是私有类型,该如何调用呢?

具体方法如下:

package com.travelsky.pss.bkg.asom.canceltest.matchsegmentinfotest;

import static org.junit.Assert.assertEquals;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import com.travelsky.pss.bkg.asom.manager.impl.cancel.CancelManagerImpl;

public class CallPrivate {

	public static void main(String args[]) throws Exception{
		Constructor<?> constructor = Reflections.class.getDeclaredConstructors()[0];
		constructor.setAccessible(true);
		Reflections reflections = (Reflections) constructor.newInstance();
		
		for(Method method : Reflections.class.getDeclaredMethods()) {
			method.setAccessible(true);
			if(method.getName().equals("matchTravellerName")) {
				String name = (String) method.invoke(reflections, "ab", "cd");
                                System.out.println(name);
			} else if (method.getName().equals("sout")) {
				method.invoke(reflections);
			}
		}
	}
}

上述做了两个关于私有方法调用的例子,一个是有参数的调用方式,一个是无参的调用方式

最终运行结果如下:

完全可以正常调用,在调用过程中一定要注意,方法和类的映射都要加入setAccessible方法,否则会报出

can not access a member of class with modifier "private"错误

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值