java - How to use Singleton for translation in java
问题描述
I want to translate a small existing java project. I should put this code in a singleton class. Now I have created a class (Taal) with a main in which the translation succeeds using ResoucreBundles. Now I need to adapt this code to the singleton class containing the methods. Now I am stuck and my question is how do I make the reference to my "Locale l"? My code so far:
package talen;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.concurrent.Callable;
public class Taal {
//private static Taal single_instance = null;
private static ResourceBundle bundle = ResourceBundle.getBundle("talen.ApplicationMessage", l); // Hoe verwijzing maken naar Locale l?
public Taal() {
// ??
}
public static String getString(String key) {
return bundle.getString(key); // String komt toe, standaard taal.
}
public static ResourceBundle getBundle() {
return bundle;
}
public static void setBundle(ResourceBundle bundle) {
Taal.bundle = bundle;
}
/*public static Taal getInstance() {
if(single_instance == null) {
single_instance = new Taal();
}
return single_instance;
// throw new IllegalArgumentException("foutboodschap");
}*/
public static void main(String[] args) {
//bepalen welke taal er moet gekozen worden
String taal = "engels";
// weten uit welke ApplicatieMessage er moet worden gekozen
String lang = "";
String country = "";
if (taal == "engels") {
lang = "eng"; //Moet gelijk zijn aan met er na _ staat in properties --> niet hoofdlettergevoelig
country = "USA";
} if (taal == "nl") {
lang = "nl"; //Moet gelijk zijn aan met er na _ staat in properties
country = "BE";
}
Locale l = new Locale(lang, country);
//algemene code om zin om te zetten
ResourceBundle bundle = ResourceBundle.getBundle("talen.ApplicationMessage", l); // talen is package naam waar properties inzitten
//wat er in de plaats moet van de zin -> tussen "" komt de variabele voor deze zin
//System.out.println(bundle.getString(key));
// Zelfde effect als lijn 65 hierboven maar met methode.
System.out.printf(getString(key));
}
}
解决方案
推荐阅读
- ios - 如何使用swift在ios的滚动视图下滚动特定视图?
- sql - SQL Select 根据多个状态字段值识别设备状态
- node.js - 如何使用 Asar 打包应用程序但不包括 Electron
- c# - C# UWP - OnNavigatedTo 触发方法两次
- r - 如何在 r 中制作交叉表
- javascript - 如何在没有用户交互的情况下自动单击第一个 Datatable 行?
- laravel - Laravel Mix 404 上的哈希不正确
- r - 如何从 R mongolite 包中查询 mongodb 集合字段名称
- android - 即使应用程序在前台,如何让 FCM 显示通知?
- arrays - swift中的struct线程安全吗