简体   繁体   中英

Can't use "this" due to static method but I have to

My main class starts with this:

public class ranks extends JavaPlugin implements Listener{

within that class, I have:

public static boolean isAdmin(String playerName){

    File adminFile = new File(this.getDataFolder() + File.separator + "admins.txt");

The problem is that I can't use "this". isAdmin MUST be static because in another class:

public class customInventory implements Listener{

I need to access it using:

if(!ranks.isAdmin(e.getPlayer().getName())){

As an overview, ranks uses methods from customInventory and vice-versa. Googling static methods and not being able to use "this" hasn't helped whatsoever.

static methods belong to the class, not a specific instance. this refers to an instance, and you don't have one. You need to make the isAdmin method an instance method (remove the static) and instantiate the rank class (with the new keyword) before calling the method.

Take a look at this answer for an explanation of static vs. instance state.

In Java, this refers to the object on which the current method is acting. But static methods don't act on objects, so there's nothing for this to refer to. If getDataFolter() is another static method, then you can call it as ranks.getDataFolder() . If it's an instance method, then you'll need to pass the relevant ranks instance into that method somehow.

this means instance of class. But isAdmin is a static method. As you see when you try to access this , it's actually never created, there is no instance which you can access.

You can make getDataFolder static an then you can call it.

Design issue can be solved by basic DI;

public class Ranks extends JavaPlugin implements Listener{
     public boolean isAdmin(String playerName){
        //rest of business logic
     }
}


public class CustomInventory implements Listener{
    private Ranks rank;

    public CustomInventory(Ranks rank) {
       this.rank = rank;
    } 


   //then call this.rank.isAdmin as usual
}

If the method getDataFolder is not inherited you can just make it static and call it without "this".

If it's inherited, so you cannot make the method static, then you need to create a static instance (singleton pattern) of rank class and use it to access the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM