java.lang.reflect.Proxy.newProxyInstance()方法示例

java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)方法返回指定接口的代理类的实例,这些接口将调用方法调用到指定的调用处理程序。

声明

以下是java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)方法的声明。

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,
   InvocationHandler h)
      throws IllegalArgumentException

参数

  • loader - 类加载器来定义代理类。
  • interfaces - 代理类实现的接口列表。
  • h - 调度处理程序调度方法调用。

返回值

  • 一个代理实例,它是具有由指定的类加载器定义并实现指定接口的代理类的指定调用处理程序的代理实例。

异常

  • IllegalArgumentException - 如果对可能传递给getProxyClass的参数有限制。
  • NullPointerException - 如果interfaces数组参数或其任何元素为空,或者调用处理程序hnull

示例

以下示例显示了java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)方法的用法。

package com.zaixian;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyDemo {
    public static void main(String[] args) throws IllegalArgumentException {
        InvocationHandler handler = new SampleInvocationHandler();
        SampleInterface proxy = (SampleInterface) Proxy.newProxyInstance(
                SampleInterface.class.getClassLoader(),
                new Class[] { SampleInterface.class }, handler);
        Class invocationHandler = Proxy.getInvocationHandler(proxy).getClass();

        System.out.println(invocationHandler.getName());
    }
}

class SampleInvocationHandler implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("Welcome To xuhuhu.com");
        return null;
    }
}

interface SampleInterface {
    void showMessage();
}

class SampleClass implements SampleInterface {
    public void showMessage() {
        System.out.println("Hello World");
    }
}

让我们编译并运行上面的程序,这将产生以下结果 -

com.zaixian.SampleInvocationHandler

上一篇: java.lang.reflect.Proxy类 下一篇: java.lang.reflect.Modifier类