Results 1 to 3 of 3

Thread: how to call class method using String

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2003
    Posts
    784

    how to call class method using String

    Hello All,

    I store class name and its method into strings.

    ie.
    String classname = "MyClass1";
    String methodname = MyMethod1";

    googling and found java.lang.reflect for doing this..

    Code:
    import java.lang.reflect.*;
    String classname = "MyClass1";
    String methodname = MyMethod1";
    Class cp1 = Class.forName(classname);
    but how to call its method?

    any help is appreciated..

    thanks & regards

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: how to call class method using String

    Well, it depends are you calling a static method or an instance method?
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2003
    Posts
    784

    Re: how to call class method using String

    just want to share ;->)

    Code:
    String fcn = "mypackage." + classname;
    Class c1 = Class.forName(fcn);
    Method meth1 = c1.getMethod("run");
    Object theObject1 = c1.newInstance();
    meth1.invoke(theObject1);

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width