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.zaixian;

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 xuhuhu.com");
        return null;
    }
}

interface SampleInterface {
    void showMessage();
}

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

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

true
Welcome To xuhuhu.com

上一篇: java.lang.reflect.Proxy类 下一篇: java.lang.reflect.Modifier类