How do you override a method for a java type instance with Groovy meta programming?

后端 未结 2 1856
旧时难觅i
旧时难觅i 2021-01-24 04:39

I am trying to override the functionality of a method of a java type instance in my Groovy code but I am getting a classcast exception.

I looked at the guide posted her

相关标签:
2条回答
  • 2021-01-24 05:02

    You are creating an ExpandoMetaClass for java.lang.String, but assigning it to a groovy.util.Proxy. Make a metaClass for groovy.util.Proxy instread, like so:

    java.lang.String hey = new java.lang.String("hey")
    def proxiedHey = new groovy.util.Proxy().wrap(hey)
    ExpandoMetaClass emc = new ExpandoMetaClass( groovy.util.Proxy, false )
    emc.substring = {
        "This is not a very good substring implementation"
    }
    emc.initialize()
    
    proxiedHey.setMetaClass(emc)
    printf proxiedHey.toString()
    printf proxiedHey.substring(1)
    
    0 讨论(0)
  • Have you looked at Pimp my Library Pattern which allows you to add using Groovy Categories. You might find it more convenient and easy to understand in your case.

    @Category(String)
    class StringSubstrCategory {      
        def substring( int n)   { 
            "This is not a very good substring implementation"
        }
    }
    
    use (StringSubstrCategory) {
        "hey".substring(1)
    }
    
    0 讨论(0)
提交回复
热议问题