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

描述

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

声明

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

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

参数

  • loader − 定义代理类的类加载器。

  • interfaces − 代理类要实现的接口列表。

  • h − 要将方法调用分派到的调用处理程序。

返回

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

异常

  • IllegalArgumentException −如果违反了传递给 getProxyClass 的参数的任何限制。

  • NullPointerException − 如果接口数组参数或其任何元素为空,或者调用处理程序 h 为空。

示例

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

package com.tutorialspoint;

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 TutorialsPoint");   
      return null;
   }
}

interface SampleInterface {
   void showMessage();
}

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

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

com.tutorialspoint.SampleInvocationHandler

java_reflect_proxy.html