Reputation: 417
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"]
Upvotes: 0
Views: 81
Reputation: 24192
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"));
Upvotes: 1
Reputation: 11
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;
}
}
Upvotes: 0
Reputation: 5658
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 ...
Upvotes: 0