Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Typecasting to a dynamic class

 
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);
da.call_func();
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?
Padma.
 
Joel McNary
Bartender
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.)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic