简体   繁体   English

如何从静态上下文引用非静态变量名?

[英]How to reference non-static variable name from static context?

I am trying to write a code that lets the user enter a team name. 我正在尝试编写一个允许用户输入团队名称的代码。 Here is my code: 这是我的代码:

public class Team {
    public String name;

    public static void main(String[] args) {
        System.out.println("Enter name team");
        Scanner tn = new Scanner(System.in);
        name = tn.nextLine();     
    }
}

I understand that "non-static variable name cannot be referenced from a static context". 我理解“无法从静态上下文中引用非静态变量名称”。 I know that if I take the "static" away from the main then it will work, but: 我知道,如果我把“静态”带离主要部分那么它会起作用,但是:

a) How can I reference it without taking the "static" out? a)如何在不“静止”的情况下引用它?

b) Is there a way to get the users input and assign it straight to the variable "name" ie without the: b)有没有办法让用户输入并直接将其分配给变量“name”,即没有:

Scanner tn = new Scanner(System.in);
name = tn.nextLine(); 

Basic questions I know, but I am still a beginner! 我知道的基本问题,但我还是初学者! Many thanks, Miles 非常感谢,迈尔斯

name is a team name. name是团队名称。 So you need to instantiate a new Team object and set its name : 因此,您需要实例化一个新的Team对象并设置其名称:

public static void main(String[] args) {
    System.out.println("Enter name team");
    Scanner tn = new Scanner(System.in);
    Team team = new Team();
    team.name = tn.nextLine();     
}

static methods do not allow to use the non-static variables directly because non-static/instance variables are initialized in memory on object creation. static方法不允许直接使用非静态变量,因为在创建对象时在内存中初始化non-static/instance变量。 Hence you need to create an object of the the class and then use the variable. 因此,您需要创建该类的对象,然后使用该变量。 Do something like this: 做这样的事情:

Team teamObj = new Team();
//now access name variable using teabObj instance
teamObj.name = tn.nextLine();    

You can use reflection as follows to access that non static field. 您可以按如下方式使用反射来访问该非静态字段。

    System.out.println("Enter name team");
    Scanner tn = new Scanner(System.in);
    Team team=new Team();
    Field field=Team.class.getField("name");
    field.set(team,tn.next());
    System.out.println((String) field.get(team));

Live demo for reflection. 现场演示反思。

Or you can try as follows. 或者你可以尝试如下。

   Team team = new Team();
   team.name = tn.nextLine();   

Live demo 现场演示

Create a Team object if you want. 如果需要,创建一个Team对象。

Team team = new Team();
team.name = tn.nextLine();

Static methods/variables are bound to class. 静态方法/变量绑定到类。 They have no access to non-static variables ( they have no idea on which instance of class they should call the method). 他们无法访问非静态变量(他们不知道应该在哪个类实例中调用该方法)。 You have to create object, and then call the non-static method. 您必须创建对象,然后调用非静态方法。

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

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