This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Typecasting to a dynamic class  RSS feed

Padma Prasad
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a problem with typecasting to a dynamic class.
What I have to do is to create an instance of a dynamic class. typecast it to the same and call a function.
Lets say my dynamic class is dyn_class. I will know this class only at runtime.
So i used............
String s = some_func.getNameoftheClass(); // some function which gets me the name of a class
Class rep = Class.forName(s); //I load the class here
Constructor con = rep.getConstructor(null); //Get the constructor for this class.
I guess I can use Constructor.newInstance(null) to get the instance of the dynamic class but newInstance returns object of type Object.I want to typecast this object to the same class which i load dynamically and call a function of it.
something like this:
dyn_class da = (dyn_class)con.newInstance(null);
but since i will know the class name only at runtime, how do i typecast the above object to the dynamic class and call the function of it?
Joel McNary
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java does not permit dynamic typecasting such as what you want.... In fact, what you are trying to do doesn't really make sense.
If you know the name of the function that you want to call, then you should also know one of:
1). The specific class that was loaded
2). A super class of the specific class
3). An interface the specific class implements.
You then cast your object to one of the three options. Generally, engineering yhour code around interfaces is a good, flexible design, so option number 3 should be preferred.
If you are loading a class that does not meet these criteria, or if you know neither the class nor the method you want to call, then you need to use Reflection (java.lang.reflect.* package) to make your function call. Just beware -- the class you load might not contain the method you try to call. (And you will get an exception at runtime instead of a compiler error at compile time.)
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!