Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-04-2012, 04:45 PM   PM User | #1
UltimateCoder
New Coder

 
Join Date: Dec 2011
Posts: 67
Thanks: 20
Thanked 1 Time in 1 Post
UltimateCoder is an unknown quantity at this point
Question Help with reflection

Being new at Java programming, please bear with me

Using reflection, I run into a problem I hope someone can help me with...


Field f = someClass.getDeclaredField("fieldName");
f.setaccessible(true);
Object fieldValue = f.get(someClass);

This is possible, but what if I don't want to use object but cast the result of f.get to a class... but this class is unknown till runtime; is that possible to do, and how should it be done?

Class x = anotherClass.newInstance();
x objectX = (x) f.get(someClass);


any help?
UltimateCoder is offline   Reply With Quote
Old 01-04-2012, 05:32 PM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,752
Thanks: 4
Thanked 2,468 Times in 2,437 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
I could probably think of a way to do this, but not like you have it here.
I don't see a reason to do this at all nonetheless. f.get would be of type object, and this can be cast, but even converting it to a runtime cast doesn't really make any difference since you cannot operate on it. It is nothing more than an Object, and with no known type in this way you wouldn't be able to compile the code if you attempt to operate on it if its a different type.
Field will have a type associated with it though, so you can pull that off of getType. That can be used in an if/elseif check to determine how to pull the data out or cast as appropriate.
Fou-Lu is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 05:39 AM.


Advertisement
Log in to turn off these ads.