Results 1 to 5 of 5
  1. #1
    ajaygargnsit is offline Member
    Join Date
    Dec 2007
    Posts
    9
    Rep Power
    0

    Default 'Casting' couch !!!!

    Well, what I need to do this.

    I have designed an interface; and two classes c1 and c2 that implement this interface. Now, I need to create an object of one of the classes (dynamically), but assign it as an interface instantiation. That is,

    interface i
    {
    void f1();
    void f2();
    }

    class c1 implements i
    {
    void f1(){}
    void f2(){}
    }

    class c2 implements i
    {
    void f1(){}
    void f2(){}
    }


    Now, I know the following will work ::

    i i_obj = new c1();
    i i_obj = new c2(); // Fine till here !!!!!!!!!!!!!!!!!!!


    But suppose I now want to the same thing, but the 'class type' must be known at run time, through the 'Properties class' object, by making use of Class.forname() function.

    NOW, how do i proceed ??

    Looking forward to reply.
    Ajay Garg

  2. #2
    ajaygargnsit is offline Member
    Join Date
    Dec 2007
    Posts
    9
    Rep Power
    0

    Default

    knock-knock !!

  3. #3
    JavaBean's Avatar
    JavaBean is offline Moderator
    Join Date
    May 2007
    Posts
    1,270
    Rep Power
    10

    Default

    What about checking it with instance of operator?

    Java Code:
    if (i_obj instanceof c1) ...

  4. #4
    jelly's Avatar
    jelly is offline Member
    Join Date
    Jan 2008
    Location
    Somerset, UK
    Posts
    46
    Rep Power
    0

    Default

    Assuming the name of the class that you want to create an instance of is in a properties object called props under the key "abc" and that the class named supports an interface called MyInterface. Code below will work as long as the class specified has an empty constructor.

    String className = props.getProperty("abc");
    Class c = Class.forName(className);
    MyInterface myInstance = (MyInterface) c.newInstance();

  5. #5
    ajaygargnsit is offline Member
    Join Date
    Dec 2007
    Posts
    9
    Rep Power
    0

    Default Vote of thanks

    Thanks jelly; your solution is correct. Its working for me.

    This thread may now be closed.

Similar Threads

  1. Casting an int value into a char
    By kurtulas in forum New To Java
    Replies: 2
    Last Post: 02-16-2008, 08:03 PM
  2. Type Casting Help
    By rhm54 in forum New To Java
    Replies: 2
    Last Post: 02-07-2008, 12:06 PM
  3. 'Casting' couch !!
    By ajaygargnsit in forum New To Java
    Replies: 1
    Last Post: 12-22-2007, 01:05 PM
  4. Casting
    By leebee in forum New To Java
    Replies: 5
    Last Post: 08-10-2007, 12:24 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
  •