Reputation: 516
So if I have a method where a variable can be an instance of a bunch of different classes where only some of them have a specific instance variable, how do I use this instance variable in the method without getting the cannot be resolved or is not a field
error?
consider this code:
void method1(){
SuperType randomInstance = getRandomInstance();
if(randomInstance.stop == true) //do something
}
where SuperType
is a super class to all possible instances that randomInstance
can hold.
However, an instance doesn't necessarily have the variable stop
so I get an error saying stop cannot be resolved or is not a field
So my question is, is there a way to get around this or would I have to create different methods for different instances depending on if they have the variable stop
or not?
Upvotes: 1
Views: 104
Reputation: 4015
If you cannot change your class hiearchy with the introdution of an Interface (Stoppable
for example) can resort to reflection to detect if the class has a provate field named stop.
You can find an example of field "listing" from a class here and Field is documented here
Upvotes: 1
Reputation: 393771
If having a stop
property can be viewed as a behavior shared by some of the sub-classes of SuperType
, you can consider defining an interface - let's call it Stoppable
- having methods getStop
(or perhaps isStopped
if it's a boolean) and setStop
.
Then your code can look like :
void method1(){
SuperType randomInstance = getRandomInstance();
if (randomInstance instanceof Stoppable) {
Stoppable sInstance = (Stoppable) randomInstance;
if(sInstance.getStop() == ...) //do something
}
}
Upvotes: 2
Reputation: 1074028
Give the classes in question a common supertype or interface (they seem, from your code, to have one — SuperType
), and define the instance field (it's not a "variable") on the supertype or define a getter function on the interface. (Actually, even if the supertype is a class, it's commonly best practice to define the field using a getter anyway, even if you could make it a public
or protected
instance field.)
Upvotes: 1