Java静态方法中调用非静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2042813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:55:23  来源:igfitidea点击:

calling non-static method in static method in Java

javastaticnon-static

提问by me123

I'm getting an error when I try to call a non-static method in a static class.

当我尝试在静态类中调用非静态方法时出现错误。

Cannot make a static reference to the non-static method methodName() from the type playback

无法从类型播放中静态引用非静态方法 methodName()

I can't make the method static as this gives me an error too.

我不能使方法静态,因为这也给我一个错误。

This static method cannot hide the instance method from xInterface

此静态方法无法从 xInterface 隐藏实例方法

Is there any way to get round calling an non-static method in another static method? (The two methods are in seperate packages and seperate classes).

有没有办法绕过在另一个静态方法中调用非静态方法?(这两种方法在单独的包和单独的类中)。

采纳答案by danben

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.

从静态方法调用非静态方法的唯一方法是拥有包含非静态方法的类的实例。根据定义,非静态方法是在某个类的实例上调用的方法,而静态方法属于类本身。

回答by Fabian Steeg

You could create an instance of the class you want to call the method on, e.g.

您可以创建要调用该方法的类的实例,例如

new Foo().nonStaticMethod();

回答by monksy

There are two ways:

有两种方式:

  1. Call the non-static method from an instance within the static method. See fabien's answer for an oneliner sample... although I would strongly recommend against it. With his example he creates an instance of the class and only uses it for one method, only to have it dispose of it later. I don't recommend it because it treats an instance like a static function.
  2. Change the static method to a non-static.
  1. 从静态方法内的实例调用非静态方法。请参阅 fabien 对 oneliner 样本的回答......尽管我强烈建议反对它。在他的例子中,他创建了一个类的实例,并且只将它用于一个方法,只是在以后处理它。我不推荐它,因为它将实例视为静态函数。
  2. 将静态方法更改为非静态方法。

回答by Drew Wills

You can't get around this restriction directly, no. But there may be some reasonable things you can do in your particular case.

你不能直接绕过这个限制,不。但是在您的特定情况下,您可能可以做一些合理的事情。

For example, you could just "new up" an instance of your class in the static method, then call the non-static method.

例如,您可以在静态方法中“新建”一个类的实例,然后调用非静态方法。

But you might get even better suggestions if you post your class(es) -- or a slimmed-down version of them.

但是如果你发布你的类——或者它们的精简版本,你可能会得到更好的建议。

回答by OscarRyz

You need an instance of the class containing the non static method.

您需要一个包含非静态方法的类的实例。

Is like when you try to invoke the non-static method startsWithof class Stringwithout an instance:

就像当您尝试在没有实例的情况下调用类的非静态方法startsWithString

 String.startsWith("Hello");

What you need is to have an instance and then invoke the non-static method:

您需要的是拥有一个实例,然后调用非静态方法:

 String greeting = new String("Hello World");
 greeting.startsWith("Hello"); // returns true 

So you need to create and instance to invoke it.

所以你需要创建和实例来调用它。

回答by Eli Acherkan

It sounds like the method really shouldbe static (i.e. it doesn't access any data members and it doesn't need an instance to be invoked on). Since you used the term "static class", I understand that the whole class is probably dedicated to utility-like methods that could be static.

听起来这个方法真的应该是静态的(即它不访问任何数据成员,也不需要调用实例)。由于您使用了“静态类”这个术语,我知道整个类可能专用于可能是静态的类似实用程序的方法。

However, Java doesn't allow the implementation of an interface-defined method to be static. So when you (naturally) try to make the method static, you get the "cannot-hide-the-instance-method" error. (The Java Language Specification mentions this in section 9.4: "Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.")

但是,Java 不允许接口定义的方法的实现是静态的。因此,当您(自然地)尝试将方法设为静态时,您会收到“无法隐藏实例方法”错误。(Java 语言规范在9.4 节中提到了这一点:“请注意,在接口中声明的方法不能声明为静态的,否则会发生编译时错误,因为静态方法不能是抽象的。”

So as long as the method is present in xInterface, and your class implements xInterface, you won't be able to make the method static.

因此,只要该方法存在于 中xInterface,并且您的类实现了xInterface,您就无法将该方法设为静态。

If you can't change the interface (or don't want to), there are several things you can do:

如果您无法更改界面(或不想更改),您可以执行以下几项操作:

  • Make the class a singleton: make the constructor private, and have a static data member in the class to hold the only existing instance. This way you'll be invoking the method on an instance, but at least you won't be creating new instances each time you need to call the method.
  • Implement 2 methods in your class: an instance method (as defined in xInterface), and a static method. The instance method will consist of a single line that delegates to the static method.
  • 使类成为单例:将构造函数设为私有,并在类中有一个静态数据成员来保存唯一存在的实例。这样,您将在实例上调用该方法,但至少您不会在每次需要调用该方法时都创建新实例。
  • 在您的类中实现 2 个方法:一个实例方法(在 中定义xInterface)和一个静态方法。实例方法将由一行委托给静态方法组成。

回答by Parmeshwar

Firstly create a class Instance and call the non-static method using that instance. e.g,

首先创建一个类 Instance 并使用该实例调用非静态方法。例如,

class demo {

    public static void main(String args[]) {
        demo d = new demo();
        d.add(10,20);     // to call the non-static method
    }

    public void add(int x ,int y) {
        int a = x;
        int b = y;
        int c = a + b;
        System.out.println("addition" + c);
    }
}

回答by JavaDeveloper

Constructor is a special method which in theory is the "only" non-static method called by any static method. else its not allowed.

构造函数是一种特殊的方法,理论上它是任何静态方法调用的“唯一”非静态方法。否则不允许。

回答by mifthi

The easiest way to use a non-static method/field within a a static method or vice versa is...

在静态方法中使用非静态方法/字段(反之亦然)的最简单方法是......

(To work this there must be at least one instance of this class)

(要做到这一点,必须至少有一个此类的实例)

This type of situation is very common in android app development eg:- An Activity has at-least one instance.

这种情况在 android 应用程序开发中很常见,例如:- 一个 Activity 至少有一个实例。

public class ParentClass{

private static ParentClass mParentInstance = null;

ParentClass(){
  mParentInstance = ParentClass.this;           
}


void instanceMethod1(){
}


static void staticMethod1(){        
    mParentInstance.instanceMethod1();
}


public static class InnerClass{
      void  innerClassMethod1(){
          mParentInstance.staticMethod1();
          mParentInstance.instanceMethod1();
      }
   }
}

Note:- This cannot be used as a builder method like this one.....

注意:- 这不能用作像这样的构建器方法.....

String.valueOf(100);

回答by george kanakis

You can call a non static method within a static one using: Classname.class.method()

您可以使用以下方法在静态方法中调用非静态方法: Classname.class.method()