View Full Version : Help with reflection

01-04-2012, 05:45 PM
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");
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?

01-04-2012, 06:32 PM
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.