国际化是一个交叉问题,因此是AOP的理想选择。使用AspectJ,你可以做这样的事情(简单,简单的例子,只是作为一个概念证明):
驱动程序:
package de.scrum_master.app;
public class Application {
public enum Language { EN, DE, FR };
public final Language language;
public Application(Language language) {
this.language = language;
}
public static void main(String[] args) {
for (Language language : Language.values())
new Application(language).printStuff();
}
private void printStuff() {
System.out.println("Hello world");
System.out.println("This error message will not be translated.");
System.out.println("one");
System.out.println("two");
System.out.println("three");
System.out.println("This error message will also not be translated.");
System.out.println("Goodbye");
System.out.println();
}
}
翻译方面:
请注意:静态翻译的东西应该存储在属性文件中。我知道这样很丑。
package de.scrum_master.aspect;
import java.util.HashMap;
import java.util.Map;
import de.scrum_master.app.Application;
import de.scrum_master.app.Application.Language;
public aspect TranslationAspect {
private static final Map<String, Map<Language, String>> dictionary = new HashMap<>();
static {
Map<Language, String> translations = new HashMap<>();
translations.put(Language.EN, "Hello world");
translations.put(Language.DE, "Hallo Welt");
translations.put(Language.FR, "Bonjour tout le monde");
dictionary.put("Hello world", translations);
translations = new HashMap<>();
translations.put(Language.EN, "Goodbye");
translations.put(Language.DE, "Auf Wiedersehen");
translations.put(Language.FR, "Au revoir");
dictionary.put("Goodbye", translations);
translations = new HashMap<>();
translations.put(Language.EN, "one");
translations.put(Language.DE, "eins");
translations.put(Language.FR, "un");
dictionary.put("one", translations);
translations = new HashMap<>();
translations.put(Language.EN, "two");
translations.put(Language.DE, "zwei");
translations.put(Language.FR, "deux");
dictionary.put("two", translations);
translations = new HashMap<>();
translations.put(Language.EN, "three");
translations.put(Language.DE, "drei");
translations.put(Language.FR, "trois");
dictionary.put("three", translations);
}
void around(Application application, String text) :
call(* *.println(String)) && this(application) && args(text)
{
proceed(
application,
dictionary.get(text) == null ? text : dictionary.get(text).get(application.language)
);
}
}
控制台输出:
Hello world
This error message will not be translated.
one
two
three
This error message will also not be translated.
Goodbye
Hallo Welt
This error message will not be translated.
eins
zwei
drei
This error message will also not be translated.
Auf Wiedersehen
Bonjour tout le monde
This error message will not be translated.
un
deux
trois
This error message will also not be translated.
Au revoir
享受!