You are not logged in.
Pages: 1
I'm writing a program where I want to have generic method for changing e.g. int variables within an object. So for instance I would have some other object invoke
fooObject.setIntStat(bar, 3)
and it would set the variable called "bar" to 3.
How, if at all, can I do this?
(And yes, I know, total noob question. )
Offline
The only way I can think of doing it would be an ugly if/else tree. I don't believe there's a dynamic solution. IMO, stick to the Java paradigm (object oriented orgasm) and write accessors and mutators. It's more verbose, but its easier to grok at a glance and is far more maintainable.
Offline
The only way I can think of doing it would be an ugly if/else tree. I don't believe there's a dynamic solution. IMO, stick to the Java paradigm (object oriented orgasm) and write accessors and mutators. It's more verbose, but its easier to grok at a glance and is far more maintainable.
Okay thanks. And oyf. That is going to be very verbose indeed.
Offline
Hmm wait a minute. What about hashmaps? Couldn't I map various strings to variable names using one?
Offline
Or maybe you could use Reflection:
http://stackoverflow.com/questions/2765 … me-in-java
Offline
Apparently Reflection can also break things hugely, and keep stuff from working in e.g. sandboxed applets.
Offline
Now Python on the other hand has a vars() method that does *exactly* what I want. Go figure.
Offline
Hmm wait a minute. What about hashmaps? Couldn't I map various strings to variable names using one?
Better solution: just keep the variables in a hash to begin with. It's what they're there for.
class Foo {
java.util.Map<String, Object> attributes;
Foo() {
this.attributes = new java.util.HashMap<String,Object>();
}
Object setAttribute(String key, Object value) {
return attributes.put(key, value);
}
Object getAttribute(String key) {
return attributes.get(key);
}
public static void main(String[] args) {
Foo obj = new Foo();
obj.setAttribute("bar", 42);
System.out.printf("bar is %d\n", obj.getAttribute("bar"));
}
}
Write accessor methods using the hash as a backend if you so desire, and replace Object with Integer if you're only interested in ints.
Now Python on the other hand has a vars() method that does *exactly* what I want. Go figure.
Python has built-ins getattr and setattr, which are more directly related to what you want and can be overridden within a class IIRC.
Offline
The only way I can think of doing it would be an ugly if/else tree. I don't believe there's a dynamic solution. IMO, stick to the Java paradigm (object oriented orgasm) and write accessors and mutators. It's more verbose, but its easier to grok at a glance and is far more maintainable.
Okay thanks. And oyf. That is going to be very verbose indeed.
Offline
Hey thanks Trent. It may take me some time to wrap my mind around, but it looks like that will work.
Offline
Pages: 1