Reloading static fields in java class

I have a class in java that has several static end lines and one static Locale variable.

These strings are basically message keys that return translated strings using locale.

ie,

public static Locale locale = Locale.getDefault();
public static String MSG1 = Translator.get(locale, "MSG1");
//Similar Strings.

This locale variable is set at runtime based on the browser locale. But since they are static variables, they are already initialized by default, and changes to the variable localehave no effect.

Is there a way to reload these lines every time a variable changes locale?

I don't want to make obvious changes (making all the lines non-static and initializing the locale in the constructor / method), because this class has many messages (250+) and is used in too many places.

+3
source share
3 answers

Yes. Although you cannot force Java to execute assignments again, you can move assignments to a method instead:

public static String MSG1;

public static void setLocale(Locale locale) {
   MSG1 = Translator.get(locale, "MSG1");
}

static {
    setLocale( Locale.getDefault() );
}

After that, you can use the method setLocale()to switch the locale. When the class is loaded for the first time, the locale is set using the static initializer block at the end.

[EDIT] , , : (= ). : - Java 1 - .

-, . . Filter .

public class I18nHelper {
    public static I18nHelper get( HttpServletRequest request ) {
        return (HttpServletRequest) request.getAttribute( "I18nHelper" );
    }

    private Locale locale;

    public I18nHelper(Locale locale) {
        this.locale = locale;
    }

    public String msg1() {
        return Translator.get(locale, "MSG1");
    }
}

: !

    public String fileNotFoundMsg( File file ) {
        ... format message with parameter "file" and return it...
    }
+6

, , , .

, :

public void doSomething() {
   if(locale.isSomeLocale()) { // Do something }
}

:

public void doSomething() {
   if(Locale.getDefault().isSomeLocale()) { // Do something }
}

, , . 200 , , , . , .

+3

But since these are static variables, they are already initialized with the default locale and changes to the locale variable do not have any effect.

You can reassign a static variable if it is not final.

+2
source

All Articles