Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Can';t使用;这";由于静态方法,但我必须_Java - Fatal编程技术网

Java Can';t使用;这";由于静态方法,但我必须

Java Can';t使用;这";由于静态方法,但我必须,java,Java,我的主要课程是这样开始的: public class ranks extends JavaPlugin implements Listener{ 在该课程中,我有: public static boolean isAdmin(String playerName){ File adminFile = new File(this.getDataFolder() + File.separator + "admins.txt"); 问题是我不能用“this”。isAdmin必须是静态的,因

我的主要课程是这样开始的:

public class ranks extends JavaPlugin implements Listener{
在该课程中,我有:

public static boolean isAdmin(String playerName){

    File adminFile = new File(this.getDataFolder() + File.separator + "admins.txt");
问题是我不能用“this”。isAdmin必须是静态的,因为在另一个类中:

public class customInventory implements Listener{
我需要通过以下方式访问它:

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

总而言之,ranks使用customInventory中的方法,反之亦然。谷歌搜索静态方法而不能使用“this”没有任何帮助。

在Java中,
this
指的是当前方法所作用的对象。但是
静态
方法不作用于对象,因此
这个
没有什么可参考的。如果
getDataFolter()
是另一个静态方法,那么可以将其称为
ranks.getDataFolder()
。如果它是一个实例方法,那么您需要以某种方式将相关的
实例传递到该方法中。

静态方法属于该类,而不是特定实例
引用一个实例,但您没有实例。在调用方法之前,需要将
isAdmin
方法设置为实例方法(删除静态)并实例化rank类(使用新关键字)


看看这个,了解静态和实例状态的解释。

这个
表示类的实例。但是
isAdmin
是一种
静态方法。正如您在尝试访问此
时所看到的,它实际上从未创建过,没有您可以访问的实例

您可以将
getDataFolder
设置为静态,然后可以调用它

设计问题可以通过基本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
}

如果方法getDataFolder没有被继承,您可以将其设置为静态,并在不使用“this”的情况下调用它


如果它是继承的,因此您不能使该方法成为静态的,那么您需要创建rank类的静态实例(单例模式),并使用它来访问该方法。

按照java惯例,将类名的第一个字母大写可能是这样。这并不能解决我的问题,尽管我觉得人们投反对票是可悲的,因为我遇到了一个问题,需要帮助解决它。这就是我写这个该死的问题的初衷。现在我的服务器上出现了一个错误,在我的排名中说“插件已经初始化了!”:
customInventory cI=new customInventory();@Override public void onEnable(){this.getServer().getPluginManager().registerEvents(this,this);
在customInventory中,我有:
ranks r=new ranks()
代码似乎有点乱:如果您实际上正在创建一个实例,并且可以通过您提到的实例访问isAdmin方法,那么为什么需要绝对静态的方法?我无法从customInventory访问ranks.isAdmin,除非isAdmin是静态的。如果isAdmin是静态的,那么我就不能使用“this”.我该怎么办?!如果我创建一个ranks anywhere的实例是因为它扩展了JavaPlugin,它将不起作用,因为你不能有多个类扩展JavaPlugingGetDataFolder是JavaPlugin中的一个方法。我不能使getDataFolder成为静态的,因为它是JavaPluginI中的一个方法。我认为你应该有设计问题sAdmin到另一个地方并提供rank实例作为方法paremeter。isAdmin需要在主类“ranks”中。isAdmin在ranks和customInventory中访问,除非我试图在customInventory中访问它,它希望我使isAdmin保持静态,然后我不能在isAdmin中使用“this”,我需要这样做。太好了!谢谢!