Results 1 to 2 of 2
  1. #1
    ranu_gokhe is offline Member
    Join Date
    Apr 2008
    Posts
    1
    Rep Power
    0

    Default How to create object dynamically with class name known in string format

    Hi,
    I'm loading a class with following statement:

    String stringToCompleteClassName = "someDynamicDigit";
    Class classToLoad = Class.forName("com.somePackage.SomeotherPackage.so meClass" + stringToCompleteClassName );

    Later i wd use reflection to get the methods of this class. now for invoking the methods with methodname.invoke() function i'd require the object of the loaded class. thus i want to create the object of the loaded class. I try to do it this way:

    Object obj = classToLoad.newInstance();

    but the problem in this is that this way i don't get the object of the class loaded but i get object of Object class.

    Now if i want to call the functions of the loaded class, i do it like:
    methodName.invoke(obj);

    it throws an exception:
    java.lang.IllegalArgumentException: object is not an instance of declaring class

    can anybody please help?
    Tell me if u need any clarification.

    thanks in advance!

  2. #2
    CaptainMorgan's Avatar
    CaptainMorgan is offline Moderator
    Join Date
    Dec 2007
    Location
    NewEngland, US
    Posts
    835
    Rep Power
    8

    Default

    After just attempting to play with this setup, I found that I needed to check for three Exceptions.... maybe a try/catch block will do?

    By the way, Welcome to the Forums!
    See you around! :)
    Vote for the new slogan to our beloved Java Forums! (closes on September 4, 2008)
    Want to voice your opinion on your IDE/Editor of choice? Vote now!
    Got a little Capt'n in you? (drink responsibly)

Similar Threads

  1. Replies: 0
    Last Post: 02-17-2008, 08:57 AM
  2. Dynamically create a button, but what happened?
    By love2java in forum AWT / Swing
    Replies: 1
    Last Post: 02-17-2008, 12:01 AM
  3. Object from String (calling method dynamically)
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-16-2008, 09:22 PM
  4. How to create widgets dynamically
    By sarbuland in forum Advanced Java
    Replies: 0
    Last Post: 02-06-2008, 08:08 PM

Posting Permissions

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