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 - 如果介面陣列引數或其任何元素為 null,或者如果呼叫處理程式 h 為 null。

示例

以下示例顯示了 java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, 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.htm
廣告
© . All rights reserved.