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

Anonymous inner class failure

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 1.7.10, 1.8.0, 3.x
    • 2.3.4
    • class generator
    • None

    Description

      Hi all,

      I found some strange behaviour using anonymous inner classes.

      If I declare (and use) an anonymous inner class inside a groovy closure inside a method, AND the anonymous inner class uses at least one of the method's input parameters, I get the following exception:

      groovy.lang.GroovyRuntimeException: Could not find matching constructor for: [className]$[closureNumber]([parameters])

          void doSomethingUsingParam(final String s1){ // This always fails
              logExceptions {
                  println "doing something (expect exception)..."
                  Runnable ifA = new Runnable(){
                              void run(){
                                  println s1
                              }
                          }
                  ifA.run()
              }
          }
      
          def logExceptions(Closure c){
              try{
                  return c.call()
              } catch (Throwable e){
                  e.printStackTrace();
              }
          }
      }
      

      I think it's a bug because the same code runs smoothly if, instead of the method input parameter, I use a local variable inside the groovy closure (the local variable doesn't even need to be declared as "final").

      void doSomethingUsingParamWorkaround(final String s2){
          logExceptions {
              println "doing something..."
              String s1=s2 // Too Ungroovy IMHO
              Runnable ifA = new Runnable(){
                          void run(){
                              println s1
                          }
                      }
              ifA.run()
          }
      }
      

      A more complete set of variants of the above methods is attached

      Attachments

        Activity

          People

            blackdrag Jochen Theodorou
            mrctrevisan Marco Trevisan
            Votes:
            2 Vote for this issue
            Watchers:
            5 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: