集册 Java实例教程 创建代理对象

创建代理对象

欢马劈雪     最近更新时间:2020-01-02 10:19:05

434
创建代理对象
/* 来自 nowjava.com - 时代Java*/


import java.lang.reflect.InvocationHandler;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;


public class Main {

  public static void main(String[] args) throws Exception {

    MyInterface myintf = (MyInterface) Proxy.newProxyInstance(

        MyInterface.class.getClassLoader(), new Class[] { MyInterface.class },

        new ProxyClass(new MyInterfaceImpl()));

    myintf.method();

  }

}


interface MyInterface {/**时 代 J a v a - nowjava.com**/

  void method();

}


class MyInterfaceImpl implements MyInterface {

  public void method() {

  }

}


class ProxyClass implements InvocationHandler {

  Object obj;


  public ProxyClass(Object o) {

    obj = o;

  }


  public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {

    Object result = null;

    try {

      result = m.invoke(obj, args);

    } 
展开阅读全文