首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

错误、信息国际化样例

2012-09-10 
异常、信息国际化样例目录:1、信息国际化2、异常国际化3、使用方法4、完整样例代码内容:1、信息国际化??? 首先,

异常、信息国际化样例

目录:

1、信息国际化

2、异常国际化

3、使用方法

4、完整样例代码

内容:

1、信息国际化

??? 首先,定义相关的properties文件,

??? 如LocalStrings_zh_CN.properties:??

EXP=\u5F02\u5E38\u56FD\u9645\u5316\u6D4B\u8BD5\!

??? 如LocalStrings_en_US.properties:

EXP=EXP+{0}+INFO

??? 然后,定义读取相关properties文件并匹配正确数据的Java类,该类主要包含的功能有:

??? a、通过ResourceBundle读取properties文件中的国际化信息,如:

ResourceBundle.getBundle(bundleName, locale,             Thread.currentThread().getContextClassLoader());

??? b、通过?ResourceBundle提供的方法进行数据读取,如:

bundle.getString(key);

??? c、通过MessageFormat类替换读取到的数据中的变量,变量的存放格式是{0}、{1}...,如:

MessageFormat mf = new MessageFormat(key);    mf.setLocale(locale);    mf.applyPattern(key);    mf.format(args);

?2、异常国际化

??? 异常的国际化是基于信息的国际化来完成的,同时也需要我们扩展运行时异常,为异常增加必要的参数,如:

package org.exception;import org.i18n.MessageBundle;/** * 自定义异常类 *  * @author orientalpigeon *  */public class CustomException extends RuntimeException{private static final long serialVersionUID = -2804635153565996548L;private String code = null;private Object[] arguments = null;public CustomException(String code){this.code = code;}public CustomException(String code,Object[] arguments){this.code = code;this.arguments = arguments;}public CustomException(String code,Object[] arguments,Throwable cause){super(cause);this.code = code;this.arguments = arguments;}public String getCode(){return this.code;}public String getMessage(){return MessageBundle.getMessage(this.code, this.arguments);}}

?? 通过上面定义,便可以通过CustomException异常类的getMessage()方法获取到对应的国际化异常信息。

3、使用方法

??? a、信息国际化????

assertEquals(MessageBundle.getMessage("EXP"), "异常国际化测试!");//设置英文locale对象CustomContext.getInstance().setLocale(new Locale("en","US"));//国际化信息中含有中变量assertEquals(MessageBundle.getMessage("EXP",new Object[]{"en_US"}), "EXP+en_US+INFO");

??? b、异常国际化

??? 不需要替换变量异常信息:

try{    throw new CustomException("EXP");}catch (CustomException e) {    assertEquals(e.getCode(), "EXP");    assertEquals(e.getMessage(), "异常国际化测试!");}

?? 需要替换变量的异常信息:

try{    //设置英文locale对象   CustomContext.getInstance().setLocale(new Locale("en","US"));    //国际化信息中含有中变量   throw new CustomException("EXP",new Object[]{"en_US"});}catch (CustomException e) {    assertEquals(e.getCode(), "EXP");    assertEquals(e.getMessage(), "EXP+en_US+INFO");}

?4、完整样例代码

?? 见附件。

热点排行