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