Results 1 to 5 of 5
Thread: 'Casting' couch !!!!
- 12-20-2007, 09:46 AM #1
Member
- Join Date
- Dec 2007
- Posts
- 9
- Rep Power
- 0
'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
- 12-20-2007, 10:32 AM #2
Member
- Join Date
- Dec 2007
- Posts
- 9
- Rep Power
- 0
knock-knock !!
- 12-20-2007, 12:29 PM #3
What about checking it with instance of operator?
Java Code:if (i_obj instanceof c1) ...
- 01-02-2008, 11:18 PM #4
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();
- 01-04-2008, 04:54 PM #5
Member
- Join Date
- Dec 2007
- Posts
- 9
- Rep Power
- 0
Similar Threads
-
Casting an int value into a char
By kurtulas in forum New To JavaReplies: 2Last Post: 02-16-2008, 08:03 PM -
Type Casting Help
By rhm54 in forum New To JavaReplies: 2Last Post: 02-07-2008, 12:06 PM -
'Casting' couch !!
By ajaygargnsit in forum New To JavaReplies: 1Last Post: 12-22-2007, 01:05 PM -
Casting
By leebee in forum New To JavaReplies: 5Last Post: 08-10-2007, 12:24 PM
Bookmarks