Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-4948

Can't extend Object#asType(Class) through metaprogramming

    XMLWordPrintableJSON

    Details

      Description

      I was going to extend my UUID class to let me convert instances to a byte array – the Groovy way, using metaprogramming.

      However, while this

              UUID.metaClass.asType = { Class clazz ->
                  UUID u = delegate
                  clazz == byte[] ? ({
                      LessSuckyByteArrayOutputStream bOut = new LessSuckyByteArrayOutputStream(16)
                      new DataOutputStream(bOut).with {
                          writeLong(u.time)
                          writeLong(u.clockSeqAndNode)
                      }
                      bOut.buf
                  })() : UUID.metaClass.asType(clazz)
              }
      

      works well for

      new UUID() as byte[]
      

      writing

      new UUID() as String
      

      now prints

      groovy.lang.ExpandoMetaClass@181b3d4[class com.eaio.uuid.UUID]
      

      Using delegate.asType(clazz) results in a StackOverflowError.

      I also tried other things but none of them worked either.

      How can I extend Object#asType(Class) for my own types while delegating to the original code otherwise?

        Attachments

          Activity

            People

            • Assignee:
              blackdrag Jochen Theodorou
              Reporter:
              johann Johann
            • Votes:
              0 Vote for this issue
              Watchers:
              0 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: