package reflectTest;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class HelloServiceProxy implements InvocationHandler{
/**
* 真实对象
*/
private Object target;
/**
* 绑定委托对象并返回一个代理类
*/
public Object bind(Object target){
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] arg2)
throws Throwable {
System.out.println("jdk动态代理");
Object result = null;
System.out.println("反射方法前");
result = method.invoke(target, arg2);
System.out.println("反射方法后");
return result;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
package reflectTest;
public interface HelloService {
public void sayHello(String name);
}
package reflectTest;
public class HelloServiceImpl implements HelloService {
@Override
public void sayHello(String name) {
System.out.println("hello"+name);
}
}
package reflectTest;
public class HelloServiceMain {
public static void main(String[] args){
HelloServiceProxy helloHandler = new HelloServiceProxy();
HelloService proxy = (HelloService)helloHandler.bind(new HelloServiceImpl());
proxy.sayHello("nicole");
}
}