Using Groovy MetaClass to overwrite Methods

后端 未结 3 1256
遥遥无期
遥遥无期 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:10

    What you have looks fine. I ran a slightly modified version on it on the groovy console webapp and it ran without issue. See for yourself using this code at http://groovyconsole.appspot.com/.

    public interface IService {
        String callX(Object o);
    }
    
    public class PlainOldJavaObject {
    
        private IService service;
    
        public String publicMethod(String x) {
            return doCallService(x);
        }
    
        public String doCallService(String x) {
            if(service == null) {
                throw new RuntimeException("Service must not be null");
            }
            return service.callX(x);
        }
    }
    
    def pojo = new PlainOldJavaObject()
    pojo.metaClass.doCallService = { String s ->
        "no service"
    }
    println pojo.publicMethod("arg")
    

    What version of Groovy are you using. It could very well be a bug in Groovy in the metaclass implementation. The groovy language moves pretty quickly and the metaclass implementation changes from version to version.

    Edit - Feedback from Comment:

    The version of the groovy console webapp is 1.7-rc-1. So it looks like that version may work as you want it to. They are currently in RC2 so I expect it would be released soon. Not sure if what you are seeing is a bug or just a difference in how it works in the 1.6.x version.

提交回复
热议问题