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;java

public class CGlibInterceptor implements MethodInterceptor {spring

    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;
    }
}apache

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;ide

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

package com.proxy.cglib;this

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

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;
    }
}ci

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

相關文章
相關標籤/搜索