Skip to content

Instantly share code, notes, and snippets.

@ngandriau
Created July 6, 2013 22:12
Show Gist options
  • Save ngandriau/5941469 to your computer and use it in GitHub Desktop.
Save ngandriau/5941469 to your computer and use it in GitHub Desktop.
Sample of failure when calling the LOG generated by the @slf4j annotation.
import groovy.util.logging.Slf4j
/**
* Created by User: ngandriau - Date: 7/6/13 - Time: 5:52 PM
*/
@Slf4j(value = "LOG")
class TestLogASTAnnotation {
static TestLogASTAnnotation staticInstanceOfMyClass = new TestLogASTAnnotation()
TestLogASTAnnotation() {
// !!! This call fails
// Caused by: java.lang.NullPointerException: Cannot invoke method info() on null object
LOG.info "constructor call"
}
def test2Log(){
// This call works
LOG.info "test in instance method"
}
public static void main(String[] args) {
// This call works
LOG.debug "test in static method"
staticInstanceOfMyClass.test2Log()
}
}
@jimwhite
Copy link

jimwhite commented Jul 7, 2013

// It's a problem with static initializer ordering. This is a simple fix.

import groovy.util.logging.Slf4j

/**

  • Created by User: ngandriau - Date: 7/6/13 - Time: 5:52 PM
    */
    @slf4j(value = "LOG")
    class TestLogASTAnnotation {

    // This must not have an initializer because LOG gets added as the last static member of the class.
    static TestLogASTAnnotation staticInstanceOfMyClass

    // This can go anywhere (and refer to any static member, regardless of where it is placed)
    // even before the member declaration above and it will still get executed after all the
    // static member initializers.
    static {
    staticInstanceOfMyClass = new TestLogASTAnnotation()
    }

    TestLogASTAnnotation() {
    // !!! This call fails
    // Caused by: java.lang.NullPointerException: Cannot invoke method info() on null object
    // logger.info "constructor call"
    LOG.info "constructor call"
    }

    def test2Log(){
    // This call works
    LOG.info "test in instance method"
    }

    public static void main(String[] args) {
    // This call works
    LOG.debug "test in static method"

    staticInstanceOfMyClass.test2Log()
    

    }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment