File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Typecasting to a dynamic class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Typecasting to a dynamic class" Watch "Typecasting to a dynamic class" New topic

Typecasting to a dynamic class

Padma Prasad
Ranch Hand

Joined: Sep 16, 2002
Posts: 76
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

Joined: Aug 20, 2001
Posts: 1824

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.)

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
I agree. Here's the link:
subject: Typecasting to a dynamic class
It's not a secret anymore!