Using Groovy MetaClass to overwrite Methods

后端 未结 3 1254
遥遥无期
遥遥无期 2021-02-01 22:52

I have a POJO that uses a service to do something:

public class PlainOldJavaObject {

    private IService service;

    public String publicMethod(String x) {
          


        
3条回答
  •  清酒与你
    2021-02-01 23:27

    If your POJO really is a Java class, and not a Groovy class, then that is your problem. Java classes don't invoke methods via the metaClass. e.g., in Groovy:

    pojo.publicMethod('arg')
    

    is equivalent to this Java:

    pojo.getMetaClass().invokeMethod('publicMethod','arg');
    

    invokeMethod sends the call through the metaClass. But this method:

    public String publicMethod(String x) {
        return doCallService(x);
    }
    

    is a Java method. It doesn't use invokeMethod to call doCallService. To get your code to work, PlainOldJavaObject needs to be a Groovy class so that all calls will go through the metaClass. Normal Java code doesn't use metaClasses.

    In short: even Groovy can't override Java method calls, it can only override calls from Groovy or that otherwise dispatch through invokeMethod.

提交回复
热议问题