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



描述

java.lang.reflect.Proxy.isProxyClass(Class<?> cl) 方法僅當已使用 getProxyClass 方法或 newProxyInstance 方法動態生成指定類以作為代理類時才返回 true。

宣告

以下是 java.lang.reflect.Proxy.isProxyClass(Class<?> cl) 方法的宣告。

public static boolean isProxyClass(Class<?> cl)

引數

cl − 要測試的類。

返回

如果類是一個代理類,則返回 true,否則返回 false。

異常

NullPointerException − 如果 cl 為 null。

示例

以下示例顯示了 java.lang.reflect.Proxy.isProxyClass(Class<?> cl) 方法的使用。

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 });
      System.out.println(Proxy.isProxyClass(proxyClass));
      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");   
   }
}

讓我們編譯並執行上述程式,這將產生以下結果 −

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