Il codice del javascript è questo:
var Player = {name: "Player", health: 100};
function getValue(propName){ //propName is a string.
return player[propName];
}
Come potrei implementarlo in Java usando le classi invece di creare un oggetto?
come se avessi un codice java che assomiglia a questo:
public class Player(){
public String name = "Player"
public int health = 100;
}
e in un'altra classe, mi piacerebbe accedere a questi valori usando stringhe come in javascript, quindi facendo Player ["salute"]
risposte:
1 per risposta № 1se sai in anticipo che il nome e la salute sono gli unici attributi che desideri:
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; }
}
e quindi puoi usare questo nel codice:
Player p = new Player ("john", 42);
System.out.println(p.getName() +""s health is " + p.getHealth());
se si desidera mantenere la flessibilità di javascript nella definizione di attributi extra in fase di esecuzione (nota: questa è considerata una cattiva pratica in java, dove type safety è una funzionalità):
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);
}
}
e poi:
Player p = new Player();
p.set("name","john");
p.set("health",42);
System.out.println(p.getAttribute("name") +""s health is " + p.getAttribute("health"));
0 per risposta № 2
Come potrei implementarlo in Java usando le classi invece di creare un oggetto?
Non so cosa intendi con questo?
Mi piacerebbe accedere a questi valori usando stringhe come in javascript, quindi facendo Player ["salute"]
Questo significa principalmente che desideri la notazione della mappa. Dai un'occhiata alle mappe Java, in particolare questo esempio Qui ...
0 per risposta № 3
Devi implementare Player come un POJO come questo:
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;
}
}