Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java "self" (static) reference

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.

like image 896
feffi Avatar asked Mar 11 '11 09:03

feffi


People also ask

What is a static reference in Java?

Static Method Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.

Can a object reference be static in Java?

The term static (in Java) means that the variable belongs to a class, not an instance or a method call. The thing here that is labelled as static is a variable. The distinction between a variable, and the value contained in a variable is critical. An object reference cannot be static.

How do you create a static instance in Java?

In Java, it is possible to create a method inside a class that can be used by itself, without reference to an instance of the class. This type of method is known as the static method. To create such a method, we've to precede its declaration with the keyword static.

How do you reference a static variable in Java?

Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.


1 Answers

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. ;)

like image 68
Peter Lawrey Avatar answered Nov 15 '22 20:11

Peter Lawrey