您的位置:首页 > 编程语言 > Java开发

Java enum枚举 测试例子

2015-10-10 16:51 453 查看

Java enum枚举

之前项目开发从来没用过Java枚举,听说很强大,所以就花一点时间研究了下。

以下是成果,代码看起来确实很简洁优雅

package test;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;

public enum Base64Util {
GBK {
public String getCharset() {
return G;
}
},

UTF8 {
public String getCharset() {
return U;
}
};
static final String G = "GBK";
static final String U = "UTF8";

/**
* 获取编码
*/
public String getCharset() {
throw new AbstractMethodError();
}

/**
* base64编码
*/
public String encodeBase64(String str) throws UnsupportedEncodingException {
try {
String charset = getCharset();
byte[] b = Base64.encodeBase64(str.getBytes(charset));
return new String(b, charset);
} catch (UnsupportedEncodingException e) {
throw e;
}
}

/**
* base64解码
*/
public String decodeBase64(String str) throws UnsupportedEncodingException {
try {
String charset = getCharset();
byte[] b = Base64.decodeBase64(str.getBytes(charset));
return new String(b, charset);
} catch (UnsupportedEncodingException e) {
throw e;
}
}
}

**测试代码**
public class TestBase64 {
public static void main(String[] args) {
System.out.println(Base64Util.G + " ---> " + Base64Util.U);
String str = "测试123";
try {
String gbkEncode2 = Base64Util.GBK.encodeBase64(str);
System.out.println(gbkEncode2);
System.out.println(Base64Util.GBK.decodeBase64(gbkEncode2));

String utf8eEncode2 = Base64Util.UTF8.encodeBase64(str);
System.out.println(utf8eEncode2);
System.out.println(Base64Util.UTF8.decodeBase64(utf8eEncode2));
} catch (Exception e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: