在Javascript中,我可以这样做:
var Services = {
Pandora : {name: "ziggy", password: "stardust"},
AppleMusic : {name: "steve", password: "jobs"},
SoundCloud : {name: "bedroom", password: "studio"}
};

使用对象表示法轻松访问数据成员
console.log(Services.Pandora.name);
console.log(Services.AppleMusic.name);
console.log(Services.SoundCloud.password);

现在,我尝试使用Java声明相同的静态变量,这让我感到困惑。我所见过的每一种方式(嵌套类,映射,ArrayLists)看起来都很复杂,并且使用了如此多的代码,以至于我很难相信在Java中没有一种简单的方法可以做到这一点。有人可以开导我吗?
后来....
我最终使用枚举,就像这样:
public enum Service {
Batanga ("Batanga","Batanga","my_name","my_password",""),
Calm ("Calm Radio","Calm Radio","my_name","my_password",""),
;
private final String svcName;
private final String svcFullName;
private final String login;
private final String pass;
private final String url;
Service(String svcName, String svcFullName, String login, String pass, String url) {
this.svcName = svcName;
this.svcFullName = svcFullName;
this.login = login;
this.pass = pass;
this.url = url;
}
public String getSvcName() {
return svcName;
}
public String getSvcFullName() {
return svcFullName;
}
public String getLogin() {
return login;
}
public String getPass(){
return pass;
}
public String getUrl() { return url; }
}

谢谢!
答案 0 :(得分:3)
好吧,我想你有一个Service
类和一个Map
类,它们都是服务名称的关键字:
class Service {
private String name, password;
public Service(String name, String password) {
this.name = name;
this.password = password;
}
// getters, setters if you'd like
}
Map<String, Service> services = new HashMap<>();
services.put("pandora", new Service("ziggy", "stardust"));
// etc.
当然,鉴于JS和Java严格打字的松散类型,两者之间会有一些显着的差异。