java.lang.reflect.Proxy.getProxyClass() Method Example



Description

The java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces) method returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces. The proxy class will be defined by the specified class loader and will implement all of the supplied interfaces. If a proxy class for the same permutation of interfaces has already been defined by the class loader, then the existing proxy class will be returned; otherwise, a proxy class for those interfaces will be generated dynamically and defined by the class loader.

Declaration

Following is the declaration for java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces) method.

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

Parameters

  • loader − the class loader to define the proxy class.

  • interfaces − the list of interfaces for the proxy class to implement.

Returns

a proxy class that is defined in the specified class loader and that implements the specified interfaces.

Exceptions

  • IllegalArgumentException − if any of the restrictions on the parameters that may be passed to getProxyClass are violated.

  • NullPointerException − if the interfaces array argument or any of its elements are null.

Example

The following example shows the usage of java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces) method.

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

Let us compile and run the above program, this will produce the following result −

Welcome to TutorialsPoint
java_reflect_proxy.htm
Advertisements