'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,
class c1 implements i
class c2 implements i
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.
What about checking it with instance of operator?
if (i_obj instanceof c1) ...
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();
Vote of thanks
Thanks jelly; your solution is correct. Its working for me.
This thread may now be closed.