Java "self" (static) reference
Asked Answered
J

4

11

I am looking for a "self" reference to the current class in JAVA in a static context manner like in PHP Scope Resolution Operator?

Solution: Break out of scope? BEWARE, this is compared to a static definition really slow (by factor 300):

static Logger LOG = LoggerFactory.getLogger(new RuntimeException().getStackTrace()[0].getClassName());

The old-fashioned way would be:

static Logger LOG = LoggerFactory.getLogger(<Classname>.class.getName());

Are there any alternatives? I'm looking for a way to put the logger definition in an abstract class. The logger should determine the class it's being called from by itself.

Jonquil answered 11/3, 2011 at 9:18 Comment(0)
D
14

The slightly faster

static final Logger LOG = LoggerFactory.getLogger(
       Thread.currentThread().getStackTrace()[0].getClassName());

If you do this 1000 times it will take 36 ms using Class.class.getName() and 60 ms doing it this way. Perhaps its not worth worrying about too much. ;)

Dakota answered 11/3, 2011 at 9:48 Comment(0)
S
4

You should not inherit logger. Just declare logger in each class.

But if you don't want do such useful think, just don't make it static)

Sympathin answered 11/3, 2011 at 9:22 Comment(0)
L
1

I don't think there are any alternatives that are significantly different to the two in your question.

You could create a helper method like this:

public static String getCallingClassname() {
    return new RuntimeException().getStackTrace()[1].getClassName();
}

and then

static Logger LOG = LoggerFactory.getLogger(Helper.getCallingClassname());

but that's as expensive as the original version. (FWIW - 300 times as slow is probably not a major concern, unless you have thousands of these loggers. Each of these statics is initialized just once ...)

My personal preference is for the "old fashioned" way of doing it.

Lemos answered 11/3, 2011 at 9:46 Comment(0)
R
0

You don't need to use any of those. What I find convenient to use is:
//Logger

private static final Logger logger = LoggerFactory.getLogger(CreateEmployeeRecord.class or this.class);

Do it in every class that needs logging, and change class name in bracket to corresponding class wherever it's being used.

Ralf answered 26/2, 2019 at 0:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.