Jdk自带的Proxy 和 cglib 处理字符串乱码的简单案例

1.proxy处理字符串乱码

//自定义代理类
public class MyProxy {
    public static Object getProxy(final Object obj){
        return  Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(method.getName().equals("get")){
                    String str = (String) method.invoke(obj,args);
                    return new String(str.getBytes("iso8859-1"),"utf-8");
                }
                return method.invoke(obj,args);
            }
        });
    }
}

测试代码

public class TestMyMap {

    public static void main(String[] args) throws UnsupportedEncodingException {
        Map proxy = (Map) MyProxy.getProxy(new MyMap());
        System.out.println(proxy.getClass());
        Map proxy2 = (Map) MyProxy.getProxy(new MyMap());
        System.out.println(proxy2.getClass());
        proxy.put("name",new String("哈哈".getBytes(),"iso8859-1"));
        System.out.println(proxy.get("name"));
    }
}

2. cglib处理字符串乱码

public class MyCGLIB {

    public static <T> T getProxy(final T obj){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(obj.getClass());
        enhancer.setCallback(new InvocationHandler() {
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                System.out.println(method.getName());
                if(method.getName().equals("put")){
                    String str = (String) objects[1];
                    //处理字符串编码
                    objects[1] = new String(str.getBytes("iso8859-1"),"utf-8");
                }
                return method.invoke(obj,objects);
            }
        });
        return (T) enhancer.create();
    }
}

测试类

public class TestCGLIB {
    public static void main(String[] args) throws UnsupportedEncodingException {
        MyMap proxy = MyCGLIB.getProxy(new MyMap());
        System.out.println(proxy.getClass());
        proxy.put("name",new String("哈哈".getBytes(),"iso8859-1"));
        System.out.println(proxy.get("name"));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值