Java dynamic proxy

Use scope

  • Java AOP is base on dynamic proxy
  • Plug in, for increasing function of package already exists.
  • Framework, for some abstract programming level.

Demo

1. an Interface

1
2
3
4
public interface Interface {
void hi();
String sayHello(String arg);
}
  • first interface used to call a method
    that has no arguments and return
  • second interface used to call a method
    that has a argument and return string

2. an implements class

1
2
3
4
5
6
7
8
9
10
11
public class HelloProxy implements Interface {
@Override
public void hi() {
System.out.println("Hello world");
}
@Override
public String sayHello(String arg) {
System.out.println("Hello " + arg);
return "Hello " + arg;
}
}
  • Geet to world
  • Geet to the input argument and return

3. an InvocationHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class DynamicProxyHandler implements InvocationHandler {

private Object proxied;

public DynamicProxyHandler(Object proxied) {
this.proxied = proxied;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {

if (args != null && args.length > 0 && args[0] != null)
return "Invoke " + method.invoke(proxied, args);

return null;
}

}
  • The handler implements InvocationHandler is the key
    to dynamic call the target methods or fields.

  • All the call in handler would be redirect to a call processor.

  • The first argument in method invoke is used to deal the
    manual call object.

  • The second argument is the method you call in a
    uppper reference or a maunal call method.

  • The third argument is the arguments you want to input,
    the processor would distinguish the method sign may be -_-.
    uppper input or maunal input arguments.

4. have a try

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.lang.reflect.Proxy;

public class SimpleDemo {

public static void main(String[] args) {
Interface hello = (Interface) Proxy.newProxyInstance(
HelloProxy.class.getClassLoader(),
new Class[] { Interface.class },
new DynamicProxyHandler(new HelloProxy()));

hello.hi();
System.out.println(hello.sayHello("proxy"));

}

}
  • The newProxyInstance will create a subClass of the second argument
    so the $proxy0 can be transform to the Interface.

  • The first argument classLoader is to point which class is agent.

  • The third argument is the handler we created in step 3
    take a proxied hello interface implement into it’s constructor.

  • The result in sayHello has been deal by handler.

Result:

Hello world
Hello proxy
Invoke Hello proxy