Java enum枚举 测试例子

来源:互联网 发布:html点击按钮执行js 编辑:程序博客网 时间:2024/06/14 03:23

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();        }    }}
0 0
原创粉丝点击