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



描述

java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces) 方法返回給定類載入器和一組介面的代理類的 java.lang.Class 物件。代理類將由指定的類載入器定義並且將實現所有提供的介面。如果類載入器已經定義了相同介面排列的代理類,那麼將返回現有的代理類;否則,將動態生成這些介面的代理類並由類載入器定義。

宣告

下面是 java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces) 方法的宣告。

public static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces)
throws IllegalArgumentException

引數

  • loader − 用於定義代理類的類載入器。

  • interfaces − 代理類要實現的介面列表。

返回

在指定類載入器中定義且實現指定介面的代理類。

異常

  • IllegalArgumentException − 如果違反任何可能傳遞給 getProxyClass 的引數限制。

  • NullPointerException − 如果介面陣列引數或其任何元素為空。

示例

以下示例展示了 java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces) 方法的用法。

package com.tutorialspoint;

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

public class ProxyDemo {
   public static void main(String[] args) throws 
      IllegalArgumentException, InstantiationException, 
         IllegalAccessException, InvocationTargetException, 
            NoSuchMethodException, SecurityException {
      InvocationHandler handler = new SampleInvocationHandler() ;

      Class proxyClass = Proxy.getProxyClass(
      SampleClass.class.getClassLoader(), new Class[] { SampleInterface.class });
      SampleInterface proxy = (SampleInterface) proxyClass.
         getConstructor(new Class[] { InvocationHandler.class }).
         newInstance(new Object[] { handler });
      proxy.showMessage();
   }
}

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

編譯並執行上述程式,它將產生以下結果 −

Welcome to TutorialsPoint
java_reflect_proxy.htm
廣告
© . All rights reserved.