Question

Why must I qualify a reference to class inside the class that it's defined in? For example:

public class Foo {
    private static Logger log = LoggerFactory.getLogger(Foo.class);
}

Why can't I just call LoggerFactory.getLogger(class) since I'm already in the context of the Foo class?

Was it helpful?

Solution

The JLS defines

15.8.2. Class Literals

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.

It wouldn't make the language ambiguous to allow class where an expression is expected to allow the syntax you describe, but it would involve overriding the keyword class to mean both

  1. a kind of declaration
  2. a reference to an instance of type Class.

The syntax you suggest might allow naming the class of an anonymous class, but getClass() would have the same meaning in anonymous classes.

Getting rid of two tokens (the unqualified class name and the .) doesn't provide much value, and it could cause confusion inside an inner class. For example, what is class inside a lambda expression?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top