國際化是一個交叉問題,因此是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
享受!