aspose file tools*
The moose likes Beginning Java and the fly likes casting with reflection ( or othre method) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "casting with reflection ( or othre method)" Watch "casting with reflection ( or othre method)" New topic
Author

casting with reflection ( or othre method)

Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
Hello all sorry for my bad english

i have problem that i need to cast object based on class's i have in my application , now my application ( depending on the deployment ) some time
have the classes and sometimes does not until now i did the casting with the full package name for example :

and as you can see if i miss one of the casting packages i will have compilation error .
can i do it more dynamically maybe with reflection or other way
so i could base on strings and i will have something like this :



i can get rune time exception no problem with that .
and i have the packages names as strings.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18715
    
  40

Something tells me that you have a bad design here. You are given an object, but you don't know the type, but you must cast it so that you can call the value() method?

Isn't it a better design to have an interface with the value() method? This way, you can cast it to the interface and call the method? And it doesn't matter what it is.

But to answer your question. If you want to use reflection, there is no need to cast it. With reflection, you can get a list of the methods, which you can traverse to find the value() method, and call it.

Henry
[ September 14, 2008: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: casting with reflection ( or othre method)