Results 1 to 4 of 4
  1. #1
    lrocha is offline Member
    Join Date
    Nov 2010
    Posts
    5
    Rep Power
    0

    Question How to Instance and reference a class by its name????

    Hi guys. I got a problem here. How can I get an instance of a specific class having the class name and casting it to the correct class type. I know that using the Class.forName("className").newInstance () will do the trick.

    But the problem is that the newInstance () method returns an Object and I need to have a reference to the specific class. The className is read from a database and I need to execute a method from that class.

    public void execute (String className, ArrayList params) {
    Class.forName (className).newInstance ();
    ........
    }

    now lets suposse className = "package.Validator"

    and I need to execute Validator.validate(params) but as I get an Object I cant execute the validate method.

    I cannot do a cast like (Validator)Class.forName (className).newInstance ();
    becausse the classname is dinamyc.

    Thanks in advance.:confused:

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    The className is read from a database and I need to execute a method from that class.

    Have a look at Invoking Methods in Oracle's Tutorial.

  3. #3
    lrocha is offline Member
    Join Date
    Nov 2010
    Posts
    5
    Rep Power
    0

    Default Solved

    Thanks a lot. It did the trick. I was not sure about it becausse I had to use a third party service that returns an Object not a Class, but everything worked with those invoking methods!

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

Similar Threads

  1. Replies: 16
    Last Post: 07-08-2010, 10:13 PM
  2. Replies: 1
    Last Post: 10-13-2009, 11:38 AM
  3. Replies: 3
    Last Post: 08-17-2009, 11:59 PM
  4. Replies: 3
    Last Post: 04-24-2009, 07:28 PM
  5. Passing Class Reference to method
    By nekt in forum Advanced Java
    Replies: 5
    Last Post: 03-26-2009, 06:08 AM

Posting Permissions

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