groovy中调用java,Groovy在Java超类中调用私有方法

I have an abstract Java class MyAbstractClass with a private method. There is a concrete implementation MyConcreteClass.

public class MyAbstractClass {

private void somePrivateMethod();

}

public class MyConcreteClass extends MyAbstractClass {

// implementation details

}

In my groovy test class I have

class MyAbstractClassTest {

void myTestMethod() {

MyAbstractClass mac = new MyConcreteClass()

mac.somePrivateMethod()

}

}

I get an error that there is no such method signature for somePrivateMethod. I know groovy can call private methods but I'm guessing the problem is that the private method is in the super class, not MyConcreteClass. Is there a way to invoke a private method in the super class like this (other than using something like PrivateAccessor)?

thanks

Jeff

解决方案

The fact that you can call private methods is a bug in the Groovy language, not a feature. However, I believe this bug was introduced deliberately as a form of compromise when making some changes to the way closures behave.

Even though you can call private methods, you should not, because hopefully one day this bug will be fixed, and if your program relies on calling private methods it will be broken.

If you really insist on (ab)using this undocumented behaviour, you could try using something like ReflectionUtils to call private methods in parent classes.

Another workaround is to provide a method in the concrete class that calls the private method in the parent class. For example, the following code "works", but it still relies on accessing private members, which is bad

class Parent {

private foo() {println "foo"}

}

class Child extends Parent {

public bar() {super.foo()}

}

new Child().bar()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值