javascript的代码是:
var Player = {name: "Player", health: 100};
function getValue(propName){ //propName is a string.
return player[propName];
}
我如何通过使用类而不是创建对象来在Java中实现它?
像我有一些看起来像这样的java代码:public class Player(){
public String name = "Player"
public int health = 100;
}
在另一个类中,我想通过使用javascript中的字符串来访问这些值,所以通过执行Player [“health”]
答案 0 :(得分:1)
如果您事先知道名称和健康是您想要的唯一属性:
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; }
}
然后你可以在代码中使用它:
Player p = new Player ("john", 42);
System.out.println(p.getName() +"'s health is " + p.getHealth());
如果你想保留javascript在运行时定义额外属性的灵活性(注意 - 这在java中被认为是不好的做法,其中类型安全是一个特性):
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);
}
}
然后:
Player p = new Player();
p.set("name","john");
p.set("health",42);
System.out.println(p.getAttribute("name") +"'s health is " + p.getAttribute("health"));
答案 1 :(得分:0)
我如何通过使用类而不是创建对象来在Java中实现它?
不知道这是什么意思?
我想通过使用javascript中的字符串来访问这些值,所以通过做播放器[“health”]
这主要意味着您需要Map符号。查看Java地图,特别是此示例here ...
答案 2 :(得分:0)
您应该将Player实现为POJO,如下所示:
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;
}
}