简体   繁体   中英

I need help translating object code from JavaScript to Java

The code of the javascript is this:

var Player = {name: "Player", health: 100};

function getValue(propName){ //propName is a string.
    return player[propName];
}

How would I implement this in Java by using classes rather than creating an object?

like I have some java code that looks like this:

public class Player(){
    public String name = "Player"
    public int health = 100;
}

and in another class, I would like to access those values by using strings like in javascript, so by doing Player["health"]

if you know in advance that name and health are the only attributes you want:

public class Player {
   private String name;
   private int health;

   public Player(String name, int health) {
      this.name = name;
      this.health = health;
   }

   public String getName() { return name; }

   public int getHealth() { return health; }
}

and then you can use this in code:

Player p = new Player ("john", 42);
System.out.println(p.getName() +"'s health is " + p.getHealth());

if you want to retain javascript's flexibility in defining extra attributes at runtime (note - this is considered bad practice in java, where type safety is a feature):

public class Player {
   private Map<String,Object> attributes = new HashMap<>();

   public void setAttribute(String name, Object value) {
      attributes.put(name,value);
   }

   public Object getAttribute(String name) {
      return attributes.get(name);
   }
}

and then:

Player p = new Player();
p.set("name","john");
p.set("health",42);
System.out.println(p.getAttribute("name") +"'s health is " + p.getAttribute("health"));

How would I implement this in Java by using classes rather than creating an object?

Don't know what you mean by this?

I would like to access those values by using strings like in javascript, so by doing Player["health"]

This mostly means you want the Map notation. Take a look into Java maps, in particular this example here ...

You should implement Player as a POJO like this:

public class Player {
    private String name;
    private int health;

    public Player() {}
    public Player(String name, int health) {
        this.name = name;
        this.health = health;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getHealth() {
        return this.health;
    }
    public void setHealth(int health) {
        this.health = health;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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