需要这个功能,但是却发现gnu提供的,还是sun的ResourceBundle都不是怎么好用,所以根据需要在resourceBundle的基础上封装了一下。
package com.csair.hunan.common;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* gettext支持类
* 主要功能:可以自动获取调用者信息,从而自动的根据local寻找resource
* (1) 查找和类名相同的properties文件
* (2) 如果(1)失败,则默认查找调用者包中的message.properties文件
* 如果找不到相应的key,不抛出异常,而是返回msgId
* 另外它支持msgId带空格,但是在properties文件中,必须把空格全部替换成下划线
* @author Alva
*
*/
public class I18NUtils {
/* A static instance holding the message */
//multi-thread safety?
public static final ThreadLocal resPool = new ThreadLocal();
public static final ThreadLocal callerPool = new ThreadLocal();
@SuppressWarnings("unchecked")
public static String _(String s) {
//get the direct caller class - FIXME how to deal with extend?
Class caller = sun.reflect.Reflection.getCallerClass(2);
ResourceBundle resourceBundle = (ResourceBundle)resPool.get();
//if no resourcebundle or the caller changed
//initial a new resource bundle
if(resourceBundle == null || !caller.equals(callerPool.get())) {
try {
// first try the property file who with the same name with the caller class
resourceBundle = ResourceBundle.getBundle(caller.getCanonicalName());
} catch(MissingResourceException missingresourceexception) {
try {
//find the default: package
resourceBundle = ResourceBundle.getBundle(caller.getPackage().getName() + ".message");
} catch (MissingResourceException e) {
//do nothing, just suppress the exception, omit the missed resource
}
}
resPool.set(resourceBundle);
//record the new caller
callerPool.set(caller);
}
try
{
// replace key's blank
String s1 = (String)resourceBundle.getObject(s.trim().replaceAll("\\p{Blank}+", "_"));
if(s1 != null)
return s1;
}
catch(MissingResourceException missingresourceexception) { }
return s;
}
}
使用起来很方便,在需要使用的类中
import static com.csair.hunan.common.I18NUtils._;
//
System.out.println(_("msgId"));
不过还欠缺一点功能:对于翻译文本中数字参数等的支持,需要加强