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"));
}
}