问题描述
我有一个抽象的Java类 MyAbstractClass
和一个私有方法。有一个具体的实现 MyConcreteClass
。
public class MyAbstractClass {
private void somePrivateMethod();
public class MyConcreteClass extends MyAbstractClass {
//实现细节
}
在我的groovy测试类中,我有
class MyAbstractClassTest {
void myTestMethod(){
MyAbstractClass mac = new MyConcreteClass()
mac.somePrivateMethod()
}
}
我得到一个错误,指出somePrivateMethod没有这样的方法签名。我知道groovy可以调用私有方法,但我猜测问题是private方法在超类中,而不是 MyConcreteClass
。有没有一种方法可以像这样在超级类中调用私有方法(除了使用像PrivateAccessor之类的方法)?
谢谢
Jeff
您可以调用私有方法的事实是,而不是功能。然而,我相信这个错误是在对封闭方式进行一些修改时故意作为一种妥协方式引入的。
即使您可以调用私有方法,您也不应该,因为希望有一天这个bug会被修复,如果你的程序依赖于调用私有方法,它将被打破。
如果你真的坚持(ab)使用这个无证行为,您可以尝试使用类似调用父类中的私有方法。
另一个解决方法是在具体类中提供一个调用父类中的私有方法的方法。例如,下面的代码有效,但它仍然依赖访问私有成员,这是不好的
class Parent {
private foo(){printlnfoo}
}
class Child extends Parent {
public bar(){super.foo()}
}
新的Child().bar()
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)?
thanksJeff
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()
这篇关于Groovy在Java超类中调用私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!