INFO_GEM_ENCHANT: "· %s &b%s"
Naming keys the way you'd name constants, and tagging them with prefixes like ERR_ and INFO_, is a pretty good approach. It makes them easy to tell apart and convenient for later color formatting.
%s lets us interpolate directly with Java's String.format.
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Set;
import static org.bukkit.Bukkit.getLogger;
public final class Messages {
private static String ERR_UNKNOWN_ITEM;
private static String ERR_UNKNOWN_COMMAND;
private static String ERR_NO_PERMISSION;
private static String ERR_PLAYER_NOT_FOUND;
private static String ERR_PLAYER_NOT_ONLINE;
// omitted...
private static String INFO_GEM_ENCHANT;
private static String INFO_UNKNOWN_ITEM;
private static String INFO_UNKNOWN_COMMAND;
private static String INFO_NO_PERMISSION;
private static String INFO_PLAYER_NOT_FOUND;
private static String INFO_PLAYER_NOT_ONLINE;
// omitted...
public static void reload(ConfigurationSection config) {
Field[] fields = Messages.class.getDeclaredFields(); // get fields via reflection
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers())) {
String key = field.getName().toLowerCase();
if (config.contains(key)) {
String message = config.getString(key);
if (key.startsWith("err_")) { // automatically color error messages
message = ChatColor.RED + message;
} else if (key.startsWith("info_")) {
message = ChatColor.GREEN + message;
}
try {
field.set(null, message);
} catch (IllegalAccessException e) {
e.printStackTrace(); // omitted
}
}
}
}
}
public static void sendToConsole(String message, Object... args) { /* ... */ }
public static void sendToPlayer(Player player, String message, Object... args) { /* ... */ }
}
This code reads every entry under the Messages section in the YML, assigns them to static variables through reflection, and automatically adds color codes for ERR_ and INFO_ messages.
It also provides two methods for sending messages to the console or to a specific player.
This code could also be improved using an enum.
The reload method should be called in the main class's onEnable method:
public void onEnable() {
// ...
Messages.reload(getConfig().getConfigurationSection("Messages"));
// ...
}
You can also call it again when the plugin reloads.
When you need to use these messages, it's just:
Messages.sendToConsole(Messages.ERR_UNKNOWN_ITEM, itemName);
Pretty clean, all things considered.
