Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic Casting?

 
Geoffrey Laurens
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Geoffrey Laurens
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for all your reply, it works.........
 
Chris Beckey
Ranch Hand
Posts: 116
Eclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
João Bispo
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 254
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
João Bispo
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 48967
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I apologize, the post was written in good faith. I'll open a new thread.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48967
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 48967
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have had to break those long lines because they exceed the width of the screen. Remember: ≤ 120 characters per line.
 
A Shehadi
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, that's right.

Thanks Campbell!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic