有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为静态变量赋值的正确方法是什么?

我试图初始化类构造函数中的变量,但IDE显示以下警告:

The static field SoapClient.url should be accessed in a static way.

你能查一下我下面的代码吗?初始化静态变量的正确方法应该是什么?我应该忽略这个警告,还是应该让变量成为非静态变量

谢谢

public class SoapClient {
    private static String url;

    public SoapClient(String url) {
        this.url = url;
    }
}

共 (6) 个答案

  1. # 1 楼答案

    正确的方法是静态方法:

    SoapClient.url = ""
    

    但这里可能需要一个常规字段:

    public class SoapClient {
        private final String url;
    
        public SoapClient(final String url) {
            this.url = url;
        }
    }
    
  2. # 2 楼答案

    有两种方法

    public Login(String url) {
        Login.url = url;
    }
    

    但是静态变量在类中只创建一次,所以为什么要在构造函数中初始化它呢。您可以创建另一个静态方法并在其中初始化url

    public static void setUrl(String url) {
        Login.url = url;
    }
    
  3. # 3 楼答案

    当变量为static时,这意味着所有实例都有一个url,而不是每个对象。您不希望对象的每个构造都改变url。然而,如果你仍然想这样做,你可以像SoapClient.url一样访问它

    (在代码中,url将始终保存最后构造的对象的值)

  4. # 4 楼答案

    拍摄from Oracle

    Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

    所以你有两个选择:

    public class SoapClient {
        private String url;
    
        public SoapClient(String url) {
            this.url = url;
        }
    }
    

    或者:

    public class SoapClient {
        private static String url = "http://stackoverflow.com";
    
        public SoapClient() {
    
        }
    }
    
  5. # 5 楼答案

    静态变量特定于类,而成员变量特定于类的实例。当我们想到SoapClient时,您可能会认为它的URL特定于类的每个不同实例,因为每个SoapClient可能有不同的URL地址

    这意味着最好从URL中删除静态关键字。 如果使用url作为成员变量,则说明已正确安装了它

    如果要将其用作静态变量,请使用:

    SoapClient.url = url;
    
  6. # 6 楼答案

    该警告来自通过this访问变量url。变量,它指的是对象的当前实例

    然而,主要的问题来自于在构造函数内部分配一个静态变量。你想要什么样的行为?你真的需要每次构建一个新的SoapClient对象时,为SoapClient的每个实例重写静态url吗?或者你需要每个客户都存储一个不同的url(我觉得这样更好)?在这种情况下,我只需像其他人建议的那样将url字段实现为常规字段(只需从字段声明中去掉static修饰符)