Java超类中的groovy调用私有方法 [英] groovy call private method in Java super class

查看:35
本文介绍了Java超类中的groovy调用私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有私有方法的抽象 Java 类 MyAbstractClass.有一个具体的实现MyConcreteClass.

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
}

在我的常规测试课中

class MyAbstractClassTest {

    void myTestMethod() {
        MyAbstractClass mac = new MyConcreteClass()
        mac.somePrivateMethod()
    }
}

我收到一个错误,提示 somePrivateMethod 没有这样的方法签名.我知道 groovy 可以调用私有方法,但我猜问题是私有方法在超类中,而不是 MyConcreteClass.有没有办法像这样调用超类中的私有方法(除了使用 PrivateAccessor 之类的东西)?

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

谢谢杰夫

推荐答案

可以调用私有方法的事实是 Groovy 语言中的错误,而不是功能.但是,我认为这个错误是在对闭包的行为方式进行一些更改时故意引入的一种妥协形式.

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.

如果你真的坚持(ab)使用这种无证行为,你可以尝试使用类似ReflectionUtils 调用父类中的私有方法.

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

这篇关于Java超类中的groovy调用私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆