Cast a class in Java

六眼飞鱼酱① 提交于 2019-12-12 05:00:38

问题


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.


回答1:


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.




回答2:


Object something = "something";
String theType = "java.lang.String";
Class<?> theClass = Class.forName(theType);
Object obj = theClass.cast(something);

This seems like a similar question: java: how can i do dynamic casting of a variable from one type to another?




回答3:


What you're looking for is probably something like this:

Class newClass = Class.forName("Interp_" + countState);
newClass.cast(yourObject);

However, without knowing the actual class at compile time, there wouldn't seem to be anything meaningful you can actually to with the properly casted value anyway, since you wouldn't be able to express any specific method calls or field references in your program without a specific class. Are you sure you aren't confused about something else? What is it that you are really trying to accomplish?



来源:https://stackoverflow.com/questions/9125671/cast-a-class-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!