prefix: "[ELD] "
first: "This is the first message"
second: "This is the second message"
third: "This is the third message"
prefix: "[ELD] "
first: "這是第一則信息"
second: "這是第二則訊息"
third: "這是第三則信息"
@GroupResource(
folder = "Langs", // 語言文件的文件夾
preloads = {"en-us", "zh-tw"} // 複製這兩個文件從 jar 內到 插件資料夾
)
@DefaultLanguage("en-us") // 定義默認語言
@Prefix(path = "prefix") // 定義prefix路徑
public class TesterMultiLang extends GroupLangConfiguration {
}
@Override
public void bindServices(ServiceCollection serviceCollection) {
serviceCollection.addMultipleLanguages(TesterMultiLang.class); // 註冊多語言文件
}
@Commander(
name = "lang",
description = "test language command"
)
public class TestLanguageCommand implements CommandNode {
@InjectPool
private GroupLang<TesterMultiLang> multiLangGroupLang;
@CommandArg(order = 1)
private String language;
@Override
public void execute(CommandSender commandSender) {
Optional<TesterMultiLang> multiLangOpt = multiLangGroupLang.getByLocale(language);
if (multiLangOpt.isEmpty()){
commandSender.sendMessage("unknown language");
return;
}
var multiLang = multiLangOpt.get();
commandSender.sendMessage(multiLang.getLang().get("first"));
commandSender.sendMessage(multiLang.getLang().get("second"));
commandSender.sendMessage(multiLang.getLang().get("third"));
}
}
public interface GroupLang<T extends GroupLangConfiguration> {
/**
* 根據 語言 id 獲取語言文件實例
* @param locale 語言 id
* @return 語言文件實例
*/
Optional<T> getByLocale(String locale);
/**
* 獲取默認語言文件實例
* @return 默認語言文件實例
*/
T getDefault();
/**
* 根據 語言 id 清除快取
* @param locale 語言 id
*/
void fetchById(String locale);
/**
* 清除所有快取
*/
void fetch();
}
public interface I18nService {
void sendMessage(Player player, String path);
void switchLanguage(Player player, String lang);
}
public class I18nServiceImpl implements I18nService {
private final Map<UUID, String> languageMap = new HashMap<>(); // 語言儲存資料庫,你應實作離線儲存
@InjectPool
private GroupLang<TesterMultiLang> languagePool;
// 根據玩家的語言發送訊息
@Override
public void sendMessage(Player player, String path) {
String lang = languageMap.getOrDefault(player.getUniqueId(), "en-us");
var langConfig = languagePool.getByLocale(lang).orElseGet(() -> {
player.sendMessage("由於沒有你的語言 (".concat(lang).concat("), 因此使用回默認語言 en-us"));
return languagePool.getDefault();
}); // 發送玩家所使用的語言的訊息, 若無則自動返回默認語言文件
player.sendMessage(langConfig.getLang().get(path));
}
// 切換語言
@Override
public void switchLanguage(Player player, String lang) {
languageMap.put(player.getUniqueId(), lang);
}
}