简体   繁体   English

在Java中的静态方法中调用非静态方法(非静态变量错误)

[英]Calling non-static method in static method in Java (Non-Static Variable Error)

I tried calling a non-static method (sA2s) in a static method (addGenCache) and my IDE (JetBrains IntelliJ) gave the 我试图调用一个非静态方法(sA2s)在一个静态方法(addGenCache)和我的IDE (JetBrains IntelliJ)

Error:(56, 27) java: non-static method sA2s(java.lang.String[]) cannot be referenced from a static context

Upon research, i discovered i had options: 经过研究,我发现我可以选择:
1) Calling an instance of the home class( Generator ): 1) 调用home类的实例( Generator ):
But the would be unhelpful giving that all the constructors for Generator are quite elaborate and i will need to use sA2s() in static context a number of times. 但是,如果Generator所有构造函数都非常复杂,那将是无济于事的,我将需要在静态上下文中多次使用sA2s()

2) Creating a subclass: 2) 创建一个子类:
I tried that here 我在这里尝试过

public static void addGenCache(String genDetails[]){
    record gen = new record("generators", true);
    try {
        sclass ss = new sclass();
        gen.writeLine(ss.sA2s(genDetails));
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("IO EXCEPTION CAUGHT");
    }
}

public class sclass{

    private String sA2s(String in[]){
        //prepare input for export
    }

}

But now i get this: 但是现在我得到了:

Error:(55, 21) java: non-static variable this cannot be referenced from a static context

Also if i try to initialize sclass as static, I get an illegal start of expression error. 另外,如果我尝试将sclass初始化为静态,则会出现illegal start of expression错误。

Can someone please analyze code and tell me what I am doing wrong? 有人可以分析代码并告诉我我做错了吗?
Also, is there an otherwise easier method to override this error? 此外,是否有其他更简便的方法来覆盖此错误?

If you want to call a non-static method (ie, an instance method) you need an instance of the class. 如果要调用非静态方法(即实例方法),则需要该类的实例。 It's as simple as that. 就这么简单。 So you have two possibilities: a) either make sure you have an instance of the class (this is your option 1), or b) make the method you want to call static. 因此,您有两种可能性:a)确保您具有该类的实例(这是您的选项1),或者b)使您要调用的方法变为静态。 Which one is best in your case depends on your specific code, which you haven't provided. 在您的情况下,哪一种最佳取决于您的特定代码(尚未提供)。

Creating a subclass does not make a method static and it does not make a non-static method callable without an instance. 创建子类不会使方法成为静态方法,也不会使没有实例的非静态方法可调用。 Anyway, in your code snippet you are not creating any subclass. 无论如何,在您的代码段中,您不会创建任何子类。

A: Create an instance 答:创建一个实例

You can call an instance method only if you have an instance of the class. 仅当您具有该类的实例时,才可以调用实例方法。 It may be that it is cumbersome to create an instance because the constructors are very elaborate, but it may be that your instance methods needs this information in order to correctly function. 创建实例可能很麻烦,因为构造函数非常复杂,但是您的实例方法可能需要此信息才能正常运行。

However, often you do not need to create a new instance every time you need to call the method; 但是,通常不需要每次都需要调用该方法时就创建一个新实例。 you can create a new instance once and use that every time: 您可以一次创建一个新实例,然后每次使用:

class Foo {
    Bar instance;

    Foo() {
       instance = new Bar(/* lots of parameters */);
    }

    void f() {
        // ...
        instance.sA2s(input1);
        // ...
        instance.sA2s(input2);
        // ...
    }
}

B: Make method static B:将方法设为静态

It can be that your method sA2a doesn't depend on any object, for example because it only accesses static variables (and local variables) and only calls static methods. 可能是您的方法sA2a不依赖于任何对象,例如,因为它仅访问静态变量(和局部变量)并且仅调用静态方法。 In that case you can make it static. 在这种情况下,您可以将其设为静态。 Static methods can be called from a static context. 可以从静态上下文中调用静态方法。

Why is sA2s private ? 为什么sA2s是私有的? Try with public. 与公众一起尝试。

A subclass might not be the best idea as maybe the parent class have complex constructors. 子类可能不是最好的主意,因为父类可能具有复杂的构造函数。 Can't you extract that logic into a Util class ? 您不能将该逻辑提取到Util类中吗?

The rule to call a non static public method is to hold a reference to the class (or subclass) that owns the method. 调用非静态公共方法的规则是持有对拥有该方法的类(或子类)的引用。

You trying to use inner class in static context as static nested. 您试图在静态上下文中将内部类用作静态嵌套。 So you should chenge it so static nested: 因此,您应该将其静态嵌套:

public static class sclass

or you can use it throw referance to upper class like this: 或者您可以使用它向上层阶级抛出引用,如下所示:

UpperClassName upperClass = new UpperClassName();
sclass ss = upperClass.new sclass();

Docs about nested classes. 有关嵌套类的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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