Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
Thread: Help with reflection
01-04-2012, 05:45 PM #1
- Join Date
- Dec 2011
- Thanked 1 Time in 1 Post
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");
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);
01-04-2012, 06:32 PM #2
- Join Date
- Sep 2002
- Saskatoon, Saskatchewan
- Thanked 2,662 Times in 2,631 Posts
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.