GeXiangDong

精通Java、SQL、Spring的拼写,擅长Linux、Windows的开关机

0%

动态的创建接口的实例

通过Proxy类动态实现一个接口 (只能是接口,可多个接口,如果需要动态创建抽象类的子类,可参照https://gist.github.com/gexiangdong/599b58566e349be40d99ee02877eb985
Raw

实现代码如下:

接口 MyInterface.java

1
2
3
4
5
6
7
/**
* 一个自定义接口,供下面的程序调用;
*/
public interface MyInterface {
public String getName();
public void setName(String name);
}

通过Proxy动态创建 MyInvocationHandler.java

也可以一次实现多个接口

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
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
* 实现InvocationHandler的类,对创建出来的类的调用都会转给此类
*/
public class MyInvocationHandler implements InvocationHandler {

public Object invoke(Object proxy, Method method, Object[] args) {
System.out.println("invoke(" + proxy.getClass().getName() + ", method:" + method.getName() + ", " + (args == null ? "NULL" : args) + ")");
if(method.getName().equals("getName")) {
return "waytt";
} else if(method.getName().equals("setName")) {
System.out.println("args " + (args != null && args.length > 0 ? args[0] : "NULL"));
return null;
}
return null;
}


public static void main(String[] argvs) throws Exception{
// 动态创建接口的程序在此
InvocationHandler handler = new MyInvocationHandler();
// 第二个参数是需要实现的接口,可以多个,一个类实现多个接口
MyInterface e = (MyInterface) Proxy.newProxyInstance(MyInterface.class.getClassLoader(),
new Class[] { MyInterface.class }, handler);
e.setName("abc");
System.out.println("getName() return " + e.getName());
}
}