在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; }
}
谢谢!
最佳答案
好吧,我想您将拥有一个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的严格类型,两者之间会有一些明显的区别。