当类名已知时,将 Object 类的 java 对象动态转换为给定的类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1893349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically converting java object of Object class to a given class when class name is known
提问by Pawka
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 objto MyClassobject? I can't write this way:
如何将该obj动态转换为MyClass对象?我不能这样写:
MyClass mobj = (MyClass)obj;
...because classNamecan be different.
...因为className可以不同。
采纳答案by Gregory Pakosz
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 MyClass
is 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).
如果MyClass
不在你的控制之下,那么你不能让它实现一些接口,另一种选择是依赖反射(参见本教程)。
回答by Chii
If you didnt know that mojb
is of type MyClass
, then how can you create that variable?
如果您不知道这mojb
是 type MyClass
,那么您如何创建该变量?
If MyClass is an interface type, or a super type, then there is no need to do a cast.
如果 MyClass 是接口类型或超类型,则无需进行强制转换。
回答by Erich Kitzmueller
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.
您不必将对象转换为 MyClass 对象,因为它已经是了。您真正想做的是强制转换它,但是由于在编译时不知道类名,因此您不能这样做,因为您不能声明该类的变量。我的猜测是您想要/需要诸如“鸭子打字”之类的东西,即您不知道类名,但在编译时知道方法名。Gregory 提出的接口是您最好的选择。
回答by Erich Kitzmueller
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);
回答by JoseJC
@SuppressWarnings("unchecked")
private static <T extends Object> T cast(Object obj) {
return (T) obj;
}