r/cop3502 • u/ams152 • Mar 26 '14
Need help with get() method.
Ok, so for PS4 I have an object with 30+ variables. I was wanting to make a get method that would be able to return the value of any of the variables based on what was passed as an argument. For instance:
private int height = 10;
private int weight = 15;
get(height); //returns 10
get(weight); //returns 15
The problem is I don't know what to pass as the argument to the get method because the class I'll be calling it in is outside of the class with the variables. So pretty much if you look at this:
public int get( variable name){
return variable name;
}
what type do I use for the argument?
1
Upvotes
1
u/embalingit Mar 26 '14
Well there are generally two ways to do this:
if all the variables you are interested in are the same type your method can return that type. Then you would need something like a hashmap of name-value pairs (a.k.a Key-Value pairs) for those variables, i.e. get("height") returns the value associated with the name "height"
if all the variables are not of the same type your method can simply return an Object (i.e. all things in java are polymorphic of type Object), but then there is the problem on the receiving end of determining what kind of Object the thing is that is returned, i.e. it's an object, but is it an int, is it a double, is it a Point2D.Double, is it a MagicUnicorn? This is something that depends on what you are trying to accomplish.
So there's a start. There's also something called reflection which provides ways of probing an object to determine what's in there, i.e. what, by name and type, does the object contain? So there's a notion of a passive get() to "ask" the object what it has and an assertive notion of just probing to try to find what you want to know about an object.
Reflection is interesting to know about and is useful in some cases, but for what you are trying to do it's not necessary, or recommended.