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.
What you're looking for is probably something like this:
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?
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.
This seems like a similar question: java: how can i do dynamic casting of a variable from one type to another?