cglib和jdk动态代理以及 按指定顺序排列list

package com.proxy.cglib;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CGlibInterceptor implements MethodInterceptor {

    private Enhancer enhancer = new Enhancer();
    private boolean useAnnotion;
    public Object builder(Class<?> targetCls, boolean useAnnotion) {
        enhancer.setSuperclass(targetCls);
        enhancer.setCallback(this);
        this.useAnnotion = useAnnotion;
        return enhancer.create();
    }
    @Override
    public Object intercept(Object target, Method method, Object[] params, MethodProxy methodProxy) throws Throwable {
        Object result = null;
        System.out.println("intercept start .....");
        Annotation[] annotations = method.getDeclaredAnnotations();
        boolean isCglib = false;
        if (useAnnotion) {
            for (Annotation annotation : annotations) {
                String annotionName = CGlibProxy.class.getName();
                String targetName = annotation.annotationType().getName();
                if (targetName.equals(annotionName)) {
                    isCglib = true;
                }
            }
        } else {
            isCglib = true;
        }
        if (isCglib) {
            System.out.println("start cglib aspectj task .....");
            // 代理类调用父类的方法
            result = methodProxy.invokeSuper(target, params);
            System.out.println("option cglib aspectj task success .....");
        }
        System.out.println("intercept end .....");
        return result;
    }
}

package com.proxy.cglib;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Inherited
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
public @interface CGlibProxy {
    String value() default "";
}

package com.proxy.cglib;

public class UserInfoService {
    
    @CGlibProxy(value="cglib")
    public String queryUser(String name) {
        System.out.println("开始查询 " + name);
        return "Lily";
    }
}

package com.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MeInvocationHandler implements InvocationHandler {
    private Object targetClass;
    private final MyAspectj myAspectj = new MyAspectj();
    public MeInvocationHandler() {}
    public MeInvocationHandler(Object targetClass) {this.targetClass = targetClass;}
    public Object biuld(Object targetClass) {
        this.targetClass = targetClass;
        return Proxy.newProxyInstance(targetClass.getClass().getClassLoader(), targetClass.getClass().getInterfaces(),this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {
        System.out.println(proxy.getClass().getSimpleName() + "前置信息通知 开始...");
        myAspectj.before();
        Object result = method.invoke(targetClass, params);
        System.out.println("通知逻辑处理开始...");
        myAspectj.after();
        return result;
    }
}

package com.proxy.jdk;
public class MyAspectj {
    public void before() {
        System.out.println("before deal with action......");
    }
    public void after() {
        System.out.println("after deal with action success......");
    }
}

package com.proxy;

import java.lang.reflect.InvocationTargetException;

import com.proxy.cglib.CGlibInterceptor;
import com.proxy.jdk.MeInvocationHandler;
import com.proxy.service.HelloService;
import com.proxy.service.HelloServiceImpl;

public class ProxyTest {
    public static void main(String[] args) {
        try {
             jdkProxyMethod();
             cglibProxyMethod(); // cglib 动态代理 创建过程缓慢,使用效率高(适用于不是频繁创建代理对象情况)
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void cglibProxyMethod() {
        CGlibInterceptor cglib = new CGlibInterceptor();
        HelloServiceImpl helloService = (HelloServiceImpl) cglib.builder(HelloServiceImpl.class, true);
        System.out.println(helloService.sayHello("Tom"));
        System.out.println(helloService.readCGlib(89008l));
    }

    private static void jdkProxyMethod() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 生成$Proxy0的class文件
//        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", true);
//        Class proxy = Proxy.getProxyClass(HelloService.class.getClassLoader(), HelloService.class);
//        Constructor proxyConst = proxy.getConstructor(InvocationHandler.class);
//        HelloService helloService = (HelloService) proxyConst
//                .newInstance(new MeInvocationHandler(new HelloServiceImpl()));
//        helloService.sayHello("Tom");

        HelloService helloService2 = (HelloService) new MeInvocationHandler().biuld(new HelloServiceImpl());
        String ret = helloService2.sayHello("Lily");
        System.out.println(ret);
    }

}

--------------- 按指定顺序排列list--------------------

package com.proxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.FixedOrderComparator;

public class SortCollection {
    public static void main(String[] args) {
        Student student1 = new Student("spring", 20, false);  
        Student student2 = new Student("summer", 18, false);  
        Student student3 = new Student("automn", 30, false);
        Student student4 = new Student("winter", 25, true);  
        List<Student> list1 = new ArrayList<Student>();  
        list1.add(student1);  
        list1.add(student3);  
        list1.add(student2);  
        list1.add(student4);
        List<Integer> ageList = new ArrayList<>();
        ageList.add(18);
        ageList.add(30);
        ageList.add(20);
        ageList.add(25);
        simpleSort(list1, ageList);
        ageList = new ArrayList<>();
        ageList.add(25);
        ageList.add(20);
        ageList.add(30);
        ageList.add(18);
        noDeopendencies(list1, ageList);
        list1.stream().forEach(val -> System.out.println(val.getName() + ":" + val.getAge()));
    }

    private static void noDeopendencies(List<Student> list1, List<Integer> ageList) {
        Collections.sort(list1, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                if (o1 == null) {
                    return -1;
                } else if (o2 == null) {
                    return 1;
                }
                return ageList.indexOf(o1.getAge()) > ageList.indexOf(o2.getAge())?1:-1;
            }
        });
    }

    private static void simpleSort(List<Student> list1, List<Integer> ageList) {
        Collections.sort(list1, new BeanComparator<Student>("age", new FixedOrderComparator(ageList)));
        list1.stream().forEach(val -> System.out.println(val.getName() + ":" + val.getAge()));
        Collections.sort(list1, new Comparator<Student>() {
            @Override
            public int compare(Student st0, Student st1) {
                return st0.getName().compareTo(st1.getName());
            }
        });
        System.out.println("----------");
    }
}
 

转载于:https://my.oschina.net/u/2510361/blog/1833573

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值