java访问私有方法

您所在的位置:网站首页 java私有成员变量语句怎么写 java访问私有方法

java访问私有方法

2023-07-22 18:49| 来源: 网络整理| 查看: 265

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"错误



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3