Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

groovy call private method in Java super class

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...