Yeah, I know. Long title of question... So I have class name in string. I'm dynamically creating object of that class in this way:
String className = "com.package.MyClass";
Class c = Class.forName(className);
Object obj = c.newInstance();
How I can dynamically convert that obj to MyClass object? I can't write this way:
MyClass mobj = (MyClass)obj;
...because className can be different.
This question is related to
java
class
object
type-conversion
If you didnt know that mojb
is of type MyClass
, then how can you create that variable?
If MyClass is an interface type, or a super type, then there is no need to do a cast.
@SuppressWarnings("unchecked")
private static <T extends Object> T cast(Object obj) {
return (T) obj;
}
You don't have to convert the object to a MyClass object because it already is. Wnat you really want to do is to cast it, but since the class name is not known at compile time, you can't do that, since you can't declare a variable of that class. My guess is that you want/need something like "duck typing", i.e. you don't know the class name but you know the method name at compile time. Interfaces, as proposed by Gregory, are your best bet to do that.
I think its pretty straight forward with reflection
MyClass mobj = MyClass.class.cast(obj);
and if class name is different
Object newObj = Class.forName(classname).cast(obj);
Source: Stackoverflow.com