JDK动态代理

一、什么是代理?

通俗的讲就是中介,通过代理,我们可以专注于业务,举个例子,假如现在我想买一辆新车,但是新车落地还需要一系列的手续,这时候可以找人帮我们完成这些手续,我们只需要专注于选择自己喜欢的车。

二、JDK动态代理实现

动态代理步骤:
1.创建被代理的接口以及其实现类

package com.wyc.service;

public interface SomeService {
    public void dosome(String name,Integer age);
    public String dother(String name);
}

接口实现类SomeServiceImpl

package com.wyc.service;

import org.springframework.stereotype.Service;


@Service("someservice")
public class SomeServiceImpl implements SomeService{

    @Override
    public void dosome(String name, Integer age) {
        System.out.println("name:"+name+",age:"+age);
    }

    @Override
    public String dother(String name) {
        System.out.println("dother方法的name值:"+name);
        return name;
    }

}

2.创建一个实现接口InvocationHandler的类,它必须实现invoke方法

package com.wyc.handler;

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

public class MyIncationHandler implements InvocationHandler{
    private Object object;

    public MyIncationHandler(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("调用dosome方法之前");
        System.out.println("method名字:"+method.getName());
        Object invoke = method.invoke(object,args);
        System.out.println("调用dosome方法之后");
        return invoke;
    }
}

3.通过Proxy的静态方法
newProxyInstance(ClassLoaderloader, Class[] interfaces, InvocationHandler h)创建一个代理后调用方法

package com;

import com.wyc.handler.MyIncationHandler;
import com.wyc.service.SomeService;
import com.wyc.service.SomeServiceImpl;
import java.lang.reflect.Proxy;

public class App
{
    public static void main( String[] args )
    {
        SomeServiceImpl someService = new SomeServiceImpl();
        MyIncationHandler myIncationHandler = new MyIncationHandler(someService);
        SomeService service = (SomeService) Proxy.newProxyInstance(someService.getClass().getClassLoader(), someService.getClass().getInterfaces(), myIncationHandler);
        service.dosome("张三",18);
    }
}

你可能感兴趣的:(Java,java)