Using Groovy MetaClass to overwrite Methods

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

    Your syntax is a tiny bit off. The problem is that pojo is a Java Object and does not have a metaClass. To intercept calls to PlainOldJavaObject's doCallService using ExpandoMetaClass:

    Just replace:

        pojo.metaClass.doCallService = { String s ->
            "no service"
        }
    

    With:

        PlainOldJavaObject.metaClass.doCallService = { String s ->
            "no service"
        }
    

提交回复
热议问题