1

In Eclipse (Java), how do I automatically add code to every class I create. Suppose I create a class called Foo, I want this code to automatically go in the preamble/state:

private final Logger log = LoggerFactory.getLogger(this.getClass());

and the appropriate slf4j import to be automatically imported. Similarly, I would like the constructor to automatically show up. Full example of what I would like to see after I click the create button:

package test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Foo {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    public Foo() {

    }

}
user2763361
  • 3,789
  • 11
  • 45
  • 81
  • Somewhere in option dialog is a way to configure templates. – talex Sep 11 '14 at 13:34
  • Alternatively, you can use [Lombok](http://projectlombok.org/) and just add `@Slf4j` annotation to your class. – Florent Bayle Sep 11 '14 at 13:40
  • You could define a Class template as described below, but a far better solution in the long run is to use code snippets produced from keyboard shortcut "slf4j"+ctrl+space, as show here https://stackoverflow.com/questions/1028858/useful-eclipse-java-code-templates – Martin of Hessle Mar 19 '19 at 15:41

2 Answers2

0

You could change the New Java Files and Class body templates to get what you want.

In the Preferences, under Java-> Code Style -> Code Templates, there is New Java Files where you would add the imports, at the appropriate place.

Imports

Change the Class body template like this

private final Logger log = LoggerFactory.getLogger(this.getClass());

public void ${type_name}() {
}

to add the logger and a default, public constructor.

Making those 2 changes will automatically add what you want when you create a new Java class file with Eclipse.

Jonathan Drapeau
  • 2,610
  • 2
  • 26
  • 32
0

This should help. You can modify whichever template suits your purpose.

code template

Praba
  • 1,373
  • 10
  • 30