aspose file tools*
The moose likes Java in General and the fly likes Dynamic Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Dynamic Casting" Watch "Dynamic Casting" New topic
Author

Dynamic Casting

Bon Truong
Greenhorn

Joined: May 08, 2003
Posts: 8
Hi,
Explicit casting is often static.
I wonder whether Java supports dynamic casting.
Let's take a look at an example:
Vector vector = null;
Object object = new Vector();
if(object instanceof java.util.Vector)
{
// I call this static casting
vector = (java.util.Vector)object;
}
Now, let's assume that I don't know the object type to cast to, but the type is a value of a String variable, i.e. "java.util.Vector".
Based on that assumption, is it possible to perform a dynamic casting?
Thanks.
Bon
Roy Tock
Ranch Hand

Joined: Jul 16, 2001
Posts: 83
Ben, help me to understand your question better... Why do you want to perform a dynamic cast?
Note that in your example, variable 'vector' has (hardcoded) class java.util.Vector; why would you want to cast variable 'object' to anything but Vector in this case?
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1817

You can dynamically test the type of the object if you wanted to (though .getClass()), but dynamic casting is right out. The reason is that casting is done at compile time, but dynamic-ness is done at run time. (I am having problems figuring out how you would use dynamic casting...I can't figure out how to write the code)


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Bon Truong
Greenhorn

Joined: May 08, 2003
Posts: 8
Roy,
Yes, you are right that it contains the hardcoded "java.util.Vector", which I call static casting. I asked the question about
dynamic casting because I am curious.
Thanks.
Bon
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Bon, there is no "dynamic casting" just because there is no need for it.
You need to cast a reference (notice that you always cast references, not objects) when you want to call a method which is not available on the type of the original reference. You either know which method you want to call at compile time, so that "static casting" suffices, or you only know it at runtime, in which case you needed to use reflection (which doesn't need casting).
So "dynamic casting" would solve a problem which doesn't exist!
Did that help?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
I would beg to differ. Java ONLY supports dynamic casting when it comes to object references. In fact, the instance of check is not necessary in the above example. You can simplify it to something like this:

Of course, this example is somewhat contrived. However, being able to cast like this is very powerful in many instances. Usually, I use this type of cast after I get() and Object from a container. Most often, I want to deal with it as something other than a generic Object.
HTH
Layne


Java API Documentation
The Java Tutorial
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1817

I suppose it depends on terminology, but to me, "dynamic casting" implies that the casting is done at runtime. "Static casting" means that the casting is done at compile time. Since casting is there primarily for the compiler's benefit, this type of casting would qualify as "static," at least as we are describing it.
"Dynamic Casting" would be something like:

This isn't really clear; I had to sort of create my own syntax for this since Java provides this capibility through Reflection, but this would essentially create a method template and build this method on the fly. You would call:

which is essentially the same as using Reflection on the object; except now you've dynamically created a method using the method template and dynamically cast the object to the passed in class -- something that is almost, but not quite, entirely unlike LISP.
As Ilja pointed out, there is no need for this type of syntax in Java, because there's no problem that it needs to solve.
As far as the instanceof check, true, it is not strictly necessary, but you could chain them together (this is bad OOP, to be sure, but I've encountered situations where, short of refactoring the Swing API, it was the only reasonable solution):

It's not pretty, but it does work. The instanceof checks there are to prevent a ClassCastException from being thrown and handled--it is better performance wise to perform a check so you don't enter a situation where an error is thrown than to blindly go in and handle the error when/if it occurrs. And in the structure above, it will occur.
[ July 22, 2003: Message edited by: Joel McNary ]
[ July 22, 2003: Message edited by: Joel McNary ]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
As I mentioned the example above is somewhat contrived. The compiler can probably optimize the cast into a static cast since it "sees" the concrete type of object. However, if it were passed as a parameter to anther method, then the cast couldn't be converted as easily. At this point it WOULD be dynamic, by your own definition. Take for example, something like this:

I'm only using Vector here since the original example used it. The principle would be the same no matter the type of object. If I understand how casting works, then this kind of cast is done at run time, and is therefore dynamic. Please correct me if I am wrong.
By way of another example, the following is quite common when retrieving data from a container:

To me this still looks like dynamic casting since the concrete type is not known at compile time. As Joel stated earlier, you could use the instanceof operator for performance reasons. However, that is not the issue of the thread. (If I were too worried about performance, I may pick a language other than Java. However, we probably don't need to open that can of worms.)
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Layne, notice that I put the phrase "dynamic casting" into quotes - I did this because I wanted to refer to the term the original poster used, but didn't think that it is well defined generally.
Bon defined his "dynamic casting" with "let's assume that I don't know the object type to cast to [at compile time], but the type is a value of a String variable". With this meaning, I stick by the claim that this is neither possible nor necessary in Java.
Jeroen Stroom
Greenhorn

Joined: Apr 09, 2003
Posts: 8
The terminology used here like dynamic and static casting is confusing.
I think we are talking about explicit casting (you specify the casting in your coding) and implicit casting (you let the compiler sort the casting out for you).
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I do wish the compiler were a little smarter some times.
String myString = myIterator.next()
The compiler tells me it can't assign Object to String. Well, you could try, couldn't you? It could throw exactly the same casting exception that it would with (String) casting.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
I do wish the compiler were a little smarter some times.
Well 1.5 should help in a number of ways. The code you give still won't compile, but you'll be able to shortcut past it, replacing

with

Also unboxing will simplify a lot of conversions involving wrapper classes - though that's further afield of what you were talking about here.


"I'm not back." - Bill Harding, Twister
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

Originally posted by Layne Lund:

(If I were too worried about performance, I may pick a language other than Java. However, we probably don't need to open that can of worms.)

It's not only about performance.
Your Code should express your thoughts, and this way you don't make clear, that you distinguish between MyClass and ! MyClass.

so, use instanceOf, if you mean instanceOf, and null, if you mean null.


http://home.arcor.de/hirnstrom/bewerbung
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Dynamic Casting