Object.factory create instance failed?
Sam Hu
samhudotsamhu at gmail.com
Thu Jun 25 00:42:20 PDT 2009
The Dmd2.030 spec. said:
static Object factory(string classname);
Create instance of class specified by classname. The class must either have no constructors or have a default constructor.
and said also:
class ClassInfo
static ClassInfo find(in char[] classname);
Search all modules for ClassInfo corresponding to classname.
Returns:
null if not found
Object create();
Create instance of Object represented by 'this'.
In below code snippet:
class Dog
{
public void bark(){}
}
int main(string[] args)
{
auto obj=Object.factory("Dog");
Dog doggie=cast(Dog)obj;
doggie.bark;
return 0;
}
Compiled successfully but failed when run:
Object.Error:Access Violation.
I also tried ClassInfo.find(string classname),ClassInfo.create() but caused the same error.
In the above code snippet,if I wrote as below:
class Dog{...}
int main(string[] args)
{
Object obj=Object.factory("Dog");
obj=new Dog; //1
Dog doggie=cast(Dog)obj;//2
doggie.bark;
return 0;
}
Everything works fine.But it seems that this does not make sense to dynamic create class instance.It is just the same as below:
Object obj;
obj=new Dog;
(cast(Dog)obj).bark;
So is there any other options can I reach the goal,i.e.,dynamically create an class instance and invoke its method?
Thanks in advance.
Regards,
Sam
More information about the Digitalmars-d-learn
mailing list