简体   繁体   中英

How to declare nested data object in java?

In Javascript, I can do this:

 var Services = { Pandora : {name: "ziggy", password: "stardust"}, AppleMusic : {name: "steve", password: "jobs"}, SoundCloud : {name: "bedroom", password: "studio"} }; 

and easily access the data members using object notation

 console.log(Services.Pandora.name); console.log(Services.AppleMusic.name); console.log(Services.SoundCloud.password); 

Now, I'm trying to declare the same static variable using Java and it is confounding me. Every way I've seen discussed (nested classes, maps, ArrayLists) seems so convoluted and uses so much code that I am having a hard time believing there is not a simple way to do this in Java. Can anybody enlighten me?

Later....

I ended up using an enum, like this:

 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; } } 

Thanks!

Well, I imagine you'd have a Service class and a Map of them which is keyed on the service name:

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.

Of course there will be some significant differences between the two given the loosely-typed nature of JS and Java's strict typing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM