Re: Get a variable value from the calling class
Mouch wrote:
I'm looking for a way to find a variable value in the calling class...
Ex :
Car myCar = new Car();
car.setName("Audi");
Wheel w = new Wheel ();
(...)
//In the Wheel class, i would like to know the name of the "calling"
Car.
//This is what I want...
String answer = wheel.getCarNameWhoCreateMyInstance(); //the result
would be audi
I know, a simple way would be to add a method in the Wheel class but I
can't...
If someone have an idea...
Thanks for any help.
rzymek@gmail.com wrote:
First of all this seems realy ugly.
It would be posible to get the calling class in this example:
class Car {
public void foo() {
setName("Audi");
Wheel w = new Wheel();
}
}
class Wheel{
public Wheel() {
//Here it would be posible to retrieve the Car instance (with
name=="Audi")
//from the call stack
}
}
It this what you need?
That won't work in general, because the Wheel instance cannot guarantee who
called it. What if it wasn't an instance of Car but of SpaceShuttle or
TvGameShow that invoked it?
The best way to do this is to put a reference in the Wheel class to the
desired information, either via a String as the OP suggests or via a reference
to the Wheel itself.
More generally one could write a proxy class that associates a Wheel and a Car
together, perhaps even Car itself:
public class Car
{
private Wheel wheel;
// accessor and mutator methods for the attribute
....
}
Anything that wants to get at the Wheel would have to go through the Car
instance to get it, picking up which Car it is as a result.
Another way is to hold an associative Map <Wheel, Car> that lets you look up
the Car for each Wheel of interest. The calling logic must have set up the
Map appropriately, of course.
--
Lew