This question already has an answer here:
I'd like to set a String, call it tag, inside class's (lets call it logger) constructor. Then tag should be based on the class that instantiated this logger and print statements with corresponding names if instantiated in different classes.
I would expect something like the below:
class Logger {
private String tag;
public Logger() {
tag = this.getClass().getEnclosingClass().getSimpleName();
}
public printTag() {
System.out.println(tag);
}
And then in the instantiating class:
Logger l = new Logger();
l.printTag();
This throws: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Class.getSimpleName()' on a null object reference
Is this possible? Is getEnclosingClass() the right method for this?
Aucun commentaire:
Enregistrer un commentaire