开发者

Dynamically converting java object of Object class to a given class when class name is known

开发者 https://www.devze.com 2022-12-13 17:47 出处:网络
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:

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:

MyCla开发者_Go百科ss mobj = (MyClass)obj;

...because className can be different.


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);


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

public interface 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).


You don't have to convert the object to a MyClass object because it already is. What 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.


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;
}


If you want to cast an object (ob1) to a class (classA), you can use the following code.

classA instance = (classA) ob1;

0

精彩评论

暂无评论...
验证码 换一张
取 消