> From: "Wim Ceulemans" <[EMAIL PROTECTED]>
> Date: Tue, 26 May 1998 08:45:30 +0200

> Does anyone has experience in passing a class as a parameter in java?

> I want to do something like call a method with as parameter a class
> name and then create instances of that class in that method. Is this
> possible?

Yes, very definitely possible.  The package java.lang.reflect contains
all the information you will need.  Many of the classes and methods of
the 'reflect' package are accessible from the class 'java.lang.Class'.

Here is simple example skeleton that contains the main steps you will
probably take in most cases.

-----------%file: WimExample.java%---------------------------
import java.lang.reflect;     // might be necessary

public class WimExample
{
  // constructors and stuff

  public void doClass(Class c)
    {
      // 1. Create instance of class
      Object obj = c.newInstance();

      // 2. Get reference to all public methods of this class
      //    returns array of _public_ methods of class defined by 'c'.
      //    The type 'Method' is defined in the 'reflect' package and
      //    contains information about the number of parameters and the
      //    type of the parameter accepted by the method in question.
      Method[] methods = obj.getMethods();

      // If you know that the 'obj' contains a method (with a particular
      // signature) then you can use (see the 'reflect' package)
      // Method m = obj.getMethod(...);

      // 3. Set up arguments for the method of your choice

      // 4. Use <chosen method>.invoke(...) to invoke the method

      // 5. Receive and process arguments returned by previous 'invoke'.
      //    'invoke' returns and instance of 'Object'.  You can use
      //    <chosen method>.getReturnType() to find out the type of
      //    object returned by the method (please see 'reflect' package).

      // 6. You will have to handle 'InvocationTargetException' which
      //    is non-runtime exception and is thrown by many of these
      //    methods.      
    }
}
-- 
Ravi/

Reply via email to