Cast a class in Java

2019-08-28 22:18发布

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.

3条回答
唯我独甜
2楼-- · 2019-08-28 22:54

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?

查看更多
聊天终结者
3楼-- · 2019-08-28 23:02

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.

查看更多
干净又极端
4楼-- · 2019-08-28 23:08
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?

查看更多
登录 后发表回答