[Solved] How do I access an instance of the logger from another class?

Hello, I am trying to access the logger from another class besides the main one, but I can not seem to think of any way to do it besides make it static. However, when I make the logger static, it gives a null pointer exception. Is there any way to access the logger from another class other than the main one?

1 Like
public class MyPlugin {

    @Inject private Logger logger;

    @Subscribe public void onInit(InitializationEvent event) {
        new SomeOtherClass(this);

    public Logger getLogger() {
        return this.logger;

public class SomeOtherClass {
    private final MyPlugin plugin;

    public SomeOtherClass(MyPlugin plugin) {
        this.plugin = plugin;

    public void doLog() {
        this.plugin.getLogger("Hello World!");
1 Like

Thanks this worked perfectly! :ok_hand:

If you want any other variables from your main class, changing this.logger to just this, then change your getLogger() to getLogger.logger

Ummm. wat? I have no idea what you just said, lol.

    public Logger getLogger() {
        return this.logger;

would become

public [MainClassName] get[MainClassName]() {
   return this;

(Replacing [MainClassName] with your main class’s name, of course)

Try that, see how it works. :smile: You’ll notice the problem soon enough, I’m sure.

That will not work unless it extends/implements (whichever it is) Logger.

This also makes no sense.

Makes complete sense to me.

@public static Main access;

@ private Game game; game = Main.access.game;

There you go. :smile: Your response earlier distinctively left out the part about needed a static access point, as well as a static method to grab it.

private static MyPlugin plugin;

public static Optional<MyPlugin> getMyPlugin() {
    return MyPlugin.plugin == null ?
        Optional.<MyPlugin>absent : 

Yeah. Also, what is the point of optionaling that?

In the case that the MyPlugin instance hasn’t been set, yet, you won’t encounter an NPE.

Well, anywhere that would need to call it shouldn’t call that before the MyPlugin instance has been called. Making it an accessible variable then calling it from another class, then setting the var in the main class to this would make a lot more sense.

You’re making a few more presumptions than anybody developing a public plugin should. The first rule of developing anything to be released to the public is “never doubt the stupidity of anyone using your software”.

1 Like

You’re not gonna call a command before the server initializes. :stuck_out_tongue:

I’m more referring to people attempting to hook into your plugin. I rather prefer to be prepared for any scenario in which a PEBKAC exception could be created.

Yeah, I guess. :slight_smile: In my case that method works because there isn’t a good reason to hook into my plugin, but in most plugins, yes. optional.