首页 > 解决方案 > 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));

    }

}

标签: javainternationalizationsingleton

解决方案


推荐阅读