简体   繁体   English

在Java超类中使用groovy调用私有方法

[英]groovy call private method in Java super class

I have an abstract Java class MyAbstractClass with a private method. 我有一个带有私有方法的抽象Java类MyAbstractClass There is a concrete implementation MyConcreteClass . 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. 我得到一个错误,即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 . 我知道groovy可以调用私有方法,但我猜测问题是私有方法是在超类中,而不是MyConcreteClass Is there a way to invoke a private method in the super class like this (other than using something like PrivateAccessor)? 有没有办法像这样调用超类中的私有方法(除了使用像PrivateAccessor这样的东西)?

thanks Jeff 谢谢Jeff

The fact that you can call private methods is a bug in the Groovy language , not a feature. 您可以调用私有方法的事实是Groovy语言中的错误 ,而不是一个功能。 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. 即使你可以调用私有方法,你也不应该这样做,因为希望有一天这个bug会被修复,如果你的程序依赖于调用私有方法,那么它将被破坏。

If you really insist on (ab)using this undocumented behaviour, you could try using something like ReflectionUtils to call private methods in parent classes. 如果你真的坚持(ab)使用这个未记录的行为,你可以尝试使用像ReflectionUtils这样的东西来调用父类中的私有方法。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM