user496949
user496949

Reputation: 86085

what does .class mean in log4j context

In log4j, I need to use

Logger.getLogger(MyClass.class);

I want to know what is the meaning of MyClass.class?

Upvotes: 0

Views: 994

Answers (3)

jamesmortensen
jamesmortensen

Reputation: 34038

.class is a property that returns the runtime instance of the class itself. You can find more information in What is a class literal in Java?.

In log4j, different loggers can be configured for different classes, so when you instantiate the logger with that class, the log level, appenders, and other configuration can be controlled for each class.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500675

It's a "class literal" - a way of getting the instance of Class<T> representing MyClass. It will give you the same result as calling this.getClass() from within an instance method of an object of type MyClass.

The Java Language Specification, section 15.8.2 has more details:

A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a . and the token class. The type of a class literal, C.Class, where C is the name of a class, interface or array type, is Class<C>. If p is the name of a primitive type, let B be the type of an expression of type p after boxing conversion (§5.1.7). Then the type of p.class is Class<B>. The type of void.class is Class.

A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.

Upvotes: 4

Logger.getLogger(MyClass.class) is used to get the full name of your class (say "com.you.package.MyClass"), and that string is used to configure this Logger object.

Log4j uses a hierarchy to determine what to do for a given logger, and the more specific instructions (say for "com.you.package") override the instructions from higher up (say for "com.you"). See the configuration file for details.

Upvotes: 0

Related Questions