*
The moose likes Beginning Java and the fly likes Dynamic Casting? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Dynamic Casting?" Watch "Dynamic Casting?" New topic
Author

Dynamic Casting?

Geoffrey Laurens
Greenhorn

Joined: Sep 19, 2006
Posts: 24
Can anybody(Java Master) help me???

How can i cast an object just by send a string parameter.
example :

and i have and Object tipe of Object.

usually we do this.


But how can i do a dynamic casting???
Rao Raghu
Ranch Hand

Joined: Jan 05, 2007
Posts: 100
You can do dynamic casting by calling a method which takes a parameter of the type you want to change your current type to. Take this for example:


public class Example{

Example e1=new Example();

private Object obj=new Object();

e1.method(obj);

public ClassName method(ClassName clsname)
{
return clsname;
}

}
Now when you call the method with obj, for executing the method it will convert the obj from Object to ClassName type.


RAGHU<br /> <br />"When the going gets tough, the tough get going"
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
If you are coming from a C++ background, ALL Java casts are like C++ dynamic_cast. That is that casting works on the real run-time type of the object, not compile-time type.

However, what you seem to be asking for does not make sense. Casting is something you do when you know, at compile-time, that the object to which you have a reference is actually of a particular subclass of the declared class of the reference. Again, it's not that Java doesn't have the facility, it's that the the suggested facility does not make sense.

Java does have lots of facilities for run-time inspection and manipulation of objects and classes. This is called "Reflection", not casting. I suggest reading the Sun tutorial, or a good equivalent, on Java Reflection.
[ January 18, 2007: Message edited by: Peter Chase ]

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Geoffrey Laurens
Greenhorn

Joined: Sep 19, 2006
Posts: 24
thanks for all your reply, it works.........
Chris Beckey
Ranch Hand

Joined: Jun 09, 2006
Posts: 116

If you are using Java 1.5 then you can do a cast by class name, though I have yet to find a situation where this would be truly useful. Anyway here is a very contrived example:

Note that the return type, after the cast, is an Object because the class name in the Class.forName() could be anything. If you knew the type when writing the code then a simple typecast would be more applicable.
Before using something like this I would take a good look at the code for a simpler and more straightforward solution. If anybody has a real reason to use this I'd be curious to hear about it.
Aaron Shaw
Greenhorn

Joined: Jan 19, 2007
Posts: 9
I don't know if this is the case, but maybe you want to be able to cast dynamically like this because you have a collection of different objects, for example, that all have the same method but implement it differently.

This kind of polymorphism could be achieved by the use of either inheritance, or implementing an interface.

The reason i'm saying all of this is because the only reason i can think of that you might want to do what you said, is because you want to implement polymorphism (the first paragraph) but without tieing in your classes to a common inheritance tree.

With the interface you can simply cast the object to that interface type, while the different object classes are completely unrelated, except that they all implement that interface.



If i'm barking completely up the wrong tree, then i apologise. I just can't think of any other reason you'd want to do that (I wrote a java application which numbered around 10 thousand lines of code when i was new, using reflection to dynamically inspect and cast objects, before i suddenly realised what interfaces were actually useful for . Now i rarely use inheritance at all. Hugely overrated, but university lecturers and many newbie books are SO bad at teaching interfaces )
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Aaron Shaw:

With the interface you can simply cast the object to that interface type, while the different object classes are completely unrelated, except that they all implement that interface.


A vanilla cast will suffice in this scenario. No "dynamic casting" needed.

The point is, to call a method other than via reflection, you need to know the type the method belongs to at compile time. So a normal type cast always suffices for this.


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
João Bispo
Greenhorn

Joined: Mar 05, 2009
Posts: 5
I could use some dynamic casting... I'm writing this more for Chris Beckey, which was curious about a use.

I have an object "library" in some programs which act as a repository of Objects (it's no more than a table with objects, with Strings as keys). It receives objects which represent information from various sources (configuration files, intermediate results from other objects). This way, the information becomes readly avaliable in any part of the program. Because I didn't want the "working" objects to be dependent on a Singleton, there is a loading object/methods which does this job: it uses the "library" object to load information into the working objects. Usually, there is a "Controller" with the main control flow of the program which calls these methods.

It doesn't need dynamic casting to work, but for each entry in the table, I need to write code, and great part of that code could be automated (i.e.: not needed to be written) if I added information about the types of the objects, in String format for example. So, the dynamic casting would not be necesary for the program to work, but would turn the class "library" more usable.


I wanted to decouple the parsing and loading of information, from the objects that use that information, and that was what I came about with. If you know better/different approaches, I'm very interested =)
Duc Vo
Ranch Hand

Joined: Nov 20, 2008
Posts: 254
João Bispo wrote:I could use some dynamic casting... I'm writing this more for Chris Beckey, which was curious about a use.

I have an object "library" in some programs which act as a repository of Objects (it's no more than a table with objects, with Strings as keys). It receives objects which represent information from various sources (configuration files, intermediate results from other objects). This way, the information becomes readly avaliable in any part of the program. Because I didn't want the "working" objects to be dependent on a Singleton, there is a loading object/methods which does this job: it uses the "library" object to load information into the working objects. Usually, there is a "Controller" with the main control flow of the program which calls these methods.

It doesn't need dynamic casting to work, but for each entry in the table, I need to write code, and great part of that code could be automated (i.e.: not needed to be written) if I added information about the types of the objects, in String format for example. So, the dynamic casting would not be necesary for the program to work, but would turn the class "library" more usable.


I wanted to decouple the parsing and loading of information, from the objects that use that information, and that was what I came about with. If you know better/different approaches, I'm very interested =)


I think what you want is not "dynamic casting" but dynamic object loading, i.e. dynamically load object state from some data source with specified type. Properly object serialization is what you should look at. Google it for more information


“Everything should be as simple as it is, but not simpler.” Albert Einstein
João Bispo
Greenhorn

Joined: Mar 05, 2009
Posts: 5
Duv Vo: Thank you for the tip. I've read about object serialization, but I'm not sure this is what I'm looking for, the life-time of the objects is limited to the program.

I'll give you an example of what I'm doing. I have a parser for a simple language, and originally, the objects would access directly the nodes of the parser tree to obtain the needed information. This had two downsides:

- The objects had to know the structure of the parser tree. If I changed the language, there might be changes in the "working" objects, which shouldn't;
- If I want to use those "working" objects (in this case, they are objects that generate code) in another context, I need an object which is a node of the parser tree, with the expected structure;

So, the initial motivation was to decouple the parser tree from the rest of the code. In this way, the "library" object is not just a table to store objects, but is also a translator - ex.: receives a node of the parser tree and transforms it into another object that better represents the data that won't change with the language, or in various simple objects like Strings, Integers and Booleans.

Is in this translation that currently I'm using normal casting to store the objects, but which I wanted to transform into a for cycle.

Again, this was a solution for decoupling a parser tree from the code that needs its information. I've already searched the internet for solutions, but haven't been lucky. If anyone knows a nice way of doing this, let me know please =)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38033
    
  22
João Bispo, it appears you are posting questions unrelated to the original topic. Please don't; you are hi-jacking Geoffrey Laurens' thread. You ought to have started a new thread.

And what was the point in opening a two-year old thread? Please read this FAQ.
João Bispo
Greenhorn

Joined: Mar 05, 2009
Posts: 5
I apologize, the post was written in good faith. I'll open a new thread.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38033
    
  22
Apology accepted. Probably best to copy the old posts into
quotes
with the "Quote" button, then people can see the old discussion.
A Shehadi
Greenhorn

Joined: Jul 13, 2009
Posts: 19
So, this is a very old post, but nonetheless keeps showing up in Google searches, so I might as well contribute to it.

You can do something like:


So what happens here is, as long as you pass a class that has a constructor with only a String as parameter (after all, if you are getting the actual value from a text file or something, you can't get any other type of data), or if you know all "dynamically" casted objects can be constructed with the same type of parameters, you can modify it to suit the parameters, like:


As you can see, I don't need to know what kind of class I'll be using to cast the value parameter, (in this case I'm hardcoding the value, but you can get it from any other data source, a file for example). Also, as long as you pass the resulting object directly to another method,
where you know exactly what to expect, this works.

Anything out of these boundaries (anyone care to correct me please? as I'm not totally sure about this) will fail, as Java is a statis typed language, not like, say Python, where objects have no "type" per se, they get their type at the time you assing a value, and the type is the one needed for this value.

Of course, if you are for example in control of what kind of classes you are going to "dynamically" load, and guarantee they will all have a constructor with the desired parameter types, you change that in the "dynamicClass.getConstructor" part and that's it.

Hope this helps someone.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38033
    
  22
I have had to break those long lines because they exceed the width of the screen. Remember: ≤ 120 characters per line.
A Shehadi
Greenhorn

Joined: Jul 13, 2009
Posts: 19
Oh, that's right.

Thanks Campbell!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Dynamic Casting?
 
Similar Threads
Dynamic Casting
Dynamic Casting
Dynamic casting using getMethod
Casting dynamic
Dynamic casting using getMethod.