在Java中投射类 [英] Cast a class in Java
问题描述
基本投放应
MyClass mc =(MyClass)aClass
这很容易
但是根据我的程序,我不知道类名直到运行时。
例如,类名可以是interp_0,interp_1,interp_2,interp_3 .......#;
现在我得到的是
Class afterCast = Class.forName(Interp_+ countState);
但我想要的是
(Interp_+ countState)afterCast
不
类afterCast
/ p>
感谢所有帮助我的人。
我建议使用所有这些类实现的接口,这些接口包含您需要的方法。然后可以转换到此接口。我不明白为什么这应该做不同,因为你知道哪些方法,你期望在那些对象是一个接口实际上。
basic casting should be
MyClass mc = (MyClass)aClass
that is easy
but based on my program, I don't know the class name until runtime.
for example, the class name could be interp_0, interp_1, interp_2, interp_3 .......#;
Is there anyway in java that I could use to cast it?
For now All I got is
Class afterCast = Class.forName("Interp_" + countState);
but what I want is
("Interp_" + countState) afterCast
, not
Class afterCast
.
Thanks for all of you who help me. It is so quick than I expected.
I would suggest using an interface implemented by all these classes which contains the methods you need. You can then cast to this interface. I don't see why this should be done different because you know which methods you expect at those objects which is an interface actually.
这篇关于在Java中投射类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!