Search code examples
javainterfacemixins

How to create Java mixins: @Slf4j


I'm trying to create a Java mixin and use the @Slf4j annotation. However intellij shows an error @Slf4j is only legal for classes and enums.

import lombok.extern.slf4j.Slf4j;

@Slf4j
public interface Foo {
    default void foo() {
        log.info("Hello world");
    }
}

Solution

  • If you want to use logging for the interface you could use a constant:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public interface Foo {
        Logger log = LoggerFactory.getLogger(Foo.class);
    
        default void foo() {
            log.info("Hello from Foo");
        }
    }
    

    If will have some implementation for this interface and you could overwrite a logger:

    public class Bar implements Foo {
        Logger log = LoggerFactory.getLogger(Bar.class);
    
        public void bar() {
            log.info("Hello from Bar");
        }
    }
    

    With Lombok it could be done even simpler:

    @Slf4j
    class Bar implements Foo {
        public void bar() {
            log.info("Hello from Bar");
        }
    }
    

    Demo code:

    public class LoggerDemo {
        public static void main(String[] args) {
            Bar bar = new Bar();
            bar.foo();
            bar.bar();
        }
    }
    

    Output:

    20:40:48.010 [main] INFO demo.Foo - Hello from Foo 
    20:40:48.014 [main] INFO demo.Bar - Hello from Bar