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

描述

当且仅当使用 getProxyClass 方法或 newProxyInstance 方法将指定类动态生成为代理类时,java.lang.reflect.Proxy.isProxyClass(Class<?> cl) 方法才返回 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.html