Search code examples
javaminecraftbukkit

How do I store a variable of a variable in bukkit?


so i've been trying to make an alt detection plugin in bukkit, i'm pretty new to the api and haven't coded in a good bit but i'm not sure on how to make it work, i've tried hashmaps and i've tried other stuff too but i still don't quite understand how to do it, Basically i'm trying to get the IP of anyone that joins that isn't already in the config and put his ip there including with his IP, and then just check if his alt joins by seeing if he has the same ip as stored already, and add him to the list of usernames that are related to the IP

I thought at the start i could do something like this:

String ip = event.getAddress().toString().replaceAll("/", "");
plugin.getConfig().set("IPs.", ip);
plugin.saveConfig();
if(plugin.getConfig().getString("IPs.") == s) {
    if(plugin.getConfig().get("IPs." + ip) == player.getName()) {
        plugin.getConfig().set("IPs." + s, player.getName());
        plugin.saveConfig();
    }
}

but i've realized I can't so i thought of trying to make a String list, and adding the list of IPs in the config, and then i realized I would need to do a weird List of lists even i technically can't then store the ip of someone and check the list of names they have since i can't check if there's a list in the name of his IP

I got really confused here, would love some help! Thanks!

EDIT 1 My HashMap code i used:

 // s is the ip string
    HashMap<String,String[]> map = new HashMap<String,String[]>();
                String[] names = new String[10];
                names[0] = player.getName();
                map.put(s, names);
                saveHashMap(map);

saveHashMap:

public void saveHashMap(HashMap<String, String[]> hm) {

    for (String key : hm.keySet()) {
        plugin.getConfig().set("IPs."+key, hm.get(key));
        }
            plugin.saveConfig();
    }

}

To test i tried this:

    HashMap<String,String[]> test = loadHashMap();
    String[] a = test.get(s);

    System.out.println(a[0]);

loadHashMap:

    public HashMap<String, String[]> loadHashMap() {
    HashMap<String, String[]> hm = new HashMap<String,String[]>();
    for (String key : plugin.getConfig().getConfigurationSection("IPs").getKeys(false)) {
        hm.put(key, (String[]) plugin.getConfig().get("IPs."+key));
        }

    return hm;
    }

Solution

  • According to the gamepedia entry you should save HashMaps like this:

    getConfig().createSection(String path, Map< String, Object > map)
    

    and retrieve them like this:

    getConfig().getConfigurationSection("path.to.map").getValues(false)
    

    You then need to cast the map to the types you want.