import net.sf.cglib.core.NamingPolicy;
import net.sf.cglib.proxy.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.jar.Attributes;
/**
* Created by geyingchao on 2017/6/9.
*/
public class Aproxy implements MethodInterceptor ,CallbackFilter {
private static final Logger LOGGER= LoggerFactory.getLogger(Aproxy.class);
public Object intercept(Object obj, Method method, Object[] arg, MethodProxy proxy) throws Throwable {
LOGGER.error("Before:"+method);
System.out.println("Before:"+method);
Object object=proxy.invokeSuper(obj, arg);
LOGGER.error("After:"+method);
System.out.println("After:"+method);
return object;
}
@Override
public int accept(Method method) {
if("methodA".equals(method.getName())){
return 0;
}else if("methodB".equals(method.getName())){
return 1;
}else if("methodC".equals(method.getName())){
return 2;
}
return 0;
}
public static Object createProxy(Object target){
Enhancer enhancer=new Enhancer();
Callback noOp= NoOp.INSTANCE;
Callback[] callbacks={new Aproxy(),noOp,new Aproxy().new InnerDefaultValue()};
enhancer.setSuperclass(target.getClass());
enhancer.setCallbacks(callbacks);
enhancer.setCallbackFilter(new Aproxy());
return enhancer.create();
}
class InnerDefaultValue implements Dispatcher{
@Override
public Object loadObject() throws Exception {
System.out.println("lazy init...");
return new Aproxy();
}
}
public String methodA(){
System.out.println("methodA");
return "methodA";
}
public String methodB(){
System.out.println("methodB");
return "methodB";
}
public String methodC(){
System.out.println("methodC");
return "methodC";
}
public static Class createInterface(Object obj){
InterfaceMaker im=new InterfaceMaker();
im.add(obj.getClass());
Class interfaceOjb=im.create();
System.out.println(interfaceOjb.isInterface());//true
System.out.println(interfaceOjb.getName());//n
return interfaceOjb;
}
public static void main(String[] args) {
Aproxy result=(Aproxy)Aproxy.createProxy(new Aproxy());
result.methodC();
Aproxy.createInterface(new Aproxy());
}
}