Hi Puneet,
>
> public class Ext1 {
>  public static String returnSomething(String sParam1) {
>  return "return from Ext1.returnSomething() with argument=" + sParam1;
> }
> }
>
> Now, my servlet contains the following code:
>  ....
>  import java.lang.reflect.*;
>  ....
>  String sApplName = "Ext1";
>  Class c = Class.forName (sApplName);
>  Object o = c.newInstance();
>
> Now, I want to invoke 'returnSomething(..)' method and get the return
string value.
>
    returnSomething() is the method of Ext1. There are two options..
1. Use a variable of Ext1 and type cast the object created using
newInstance. Invoke the method directly.

2. If the method to be invoked is going to remain same but the class to be
instantiated is different i.e. Ext1, or Ext2 etc then you can have a
superclass with the specified method or an interface defining that method.
All the classes Ext1, Ext2 will extend/implement that one. Now again use the
variable of superclass/interface and invoke the method after typecasting the
object instance created.

3. If this is still not the case and the method name is also going to vary,
then use reflection for invoking the method. You can get the method from the
class using Class.getMethod(String, Class[]) or
Class.getDeclaredMethod(String, Class[]). This will return you the object of
java.lang.reflect.Method. Use invoke method on this now.
public Object invoke(Object obj, Object[] args) throws
IllegalAccessException, IllegalArgumentException,
InvocationTargetException

Hope this helps.
-sourabh

___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".

Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html

Reply via email to