G
Gandu
Could some Java Guru please help me? I have the following problem:
Given the name of a class(e.g. MyClass), I can use use the methods of
the Class class as:
Class myClass = Class.forName(MyClass);
Object obj = myClass.newInstance();
The problem here is that the type of obj is Object, NOT MyClass. Of
course, I can cast it as
MyClass myClassNew = (MyClass)obj;
Now, my question is:
How do I do this dynamically? That is, suppose for example I am looking
at all Java classes in a directory. I pick out a Java class(check if the
file name extension is .java) and then I want to create an instance of it.
The class name is obviously stored in some String variable - but how do I
use it to create an instance of the specified class, NOT Object. To be
more specific, suppose I have the method:
public Object getInstance(String className){
try{
Class cls = Class.forName(className);
return cls.newInstance();
}
catch(Exception ex){
//
}
return null;
}
Now how do I re-cast the object returned(of type Object) to its original
type(stored in String className).
Any help would be greatly appreciated.
Given the name of a class(e.g. MyClass), I can use use the methods of
the Class class as:
Class myClass = Class.forName(MyClass);
Object obj = myClass.newInstance();
The problem here is that the type of obj is Object, NOT MyClass. Of
course, I can cast it as
MyClass myClassNew = (MyClass)obj;
Now, my question is:
How do I do this dynamically? That is, suppose for example I am looking
at all Java classes in a directory. I pick out a Java class(check if the
file name extension is .java) and then I want to create an instance of it.
The class name is obviously stored in some String variable - but how do I
use it to create an instance of the specified class, NOT Object. To be
more specific, suppose I have the method:
public Object getInstance(String className){
try{
Class cls = Class.forName(className);
return cls.newInstance();
}
catch(Exception ex){
//
}
return null;
}
Now how do I re-cast the object returned(of type Object) to its original
type(stored in String className).
Any help would be greatly appreciated.