views:

198

answers:

3

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.

+4  A: 

you don't, declare an interface that declares the methods you would like to call:

public MyInterface
{
  void doStuff();
}

public class MyClass implements MyInterface
{
  public void doStuff()
  {
    System.Console.Writeln("done!");
  }
}

then you use

MyInterface mobj = (myInterface)obj;
mobj.doStuff();

If MyClassis not under your control then you can't make it implement some interface, and the other option is to rely on reflection (see this tutorial).

Gregory Pakosz
Although I do agree with Greg in most cases; I found myself in a situation where I don't want to have to know about interfaces. I don't know if that tutorial above addressed this issue, but none of those I'd found in my research on the issue did. Here's a dynamic solution I came up with (you would need to know the name of the method/field as well as the name of the class): http://forums.sun.com/thread.jspa?threadID=5419973
nomad311
+2  A: 

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.

Chii
+1  A: 

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.

ammoQ
If you really need this sort of feature, consider another language - groovy is one that runs on the jvm but has the feature you want.
Chii