Created
July 20, 2017 02:23
-
-
Save dumptruckman/ca4d6a9c9a83ce3b9f152d82e2e59ed5 to your computer and use it in GitHub Desktop.
ConfigUtil (for Lists of any type)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.bukkit.configuration.ConfigurationSection; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.Map; | |
public class ConfigUtil { | |
/** | |
* Retrieves a list from the given config section at the given path containing only elements of the given type. | |
* | |
* @param section The config section to get the list from. | |
* @param path The path of the list within the given config section. | |
* @param type The desired generic type of the list. | |
* @return A list of all the objects of the give type at the given path within the given config section which could | |
* be empty if the path does not represent a list or there are no objects of the given type in that list. | |
*/ | |
public static <T> List<T> getList(ConfigurationSection section, String path, Class<T> type) { | |
List<?> wildList = section.getList(path, Collections.emptyList()); | |
return convertToTypedList(wildList, type); | |
} | |
/** | |
* Retrieves a list from the given map with the given key containing only elements of the given type. | |
* | |
* @param serializedData The map that contains the desired list. | |
* @param key The map key for the list. | |
* @param type The desired generic type of the list. | |
* @return A list of all the objects of the give type for the given key within the given map which could be empty | |
* if none value for the key does not represent a list or there are no objects of the given type in that list. | |
*/ | |
public static <T> List<T> getList(Map<String, Object> serializedData, String key, Class<T> type) { | |
Object o = serializedData.get(key); | |
List<?> wildList; | |
if (o instanceof List) { | |
wildList = (List<?>) o; | |
} else { | |
wildList = Collections.emptyList(); | |
} | |
return convertToTypedList(wildList, type); | |
} | |
// Helper method for the getList methods. | |
private static <T> List<T> convertToTypedList(List<?> wildList, Class<T> type) { | |
List<T> result = new ArrayList<>(wildList.size()); | |
for (Object o : wildList) { | |
if (type.isInstance(o)) { | |
result.add((T) o); | |
} | |
} | |
return result; | |
} | |
// This is a singleton... you shouldn't be instantiating it. | |
private ConfigUtil() { | |
throw new AssertionError(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment