1

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?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
PandaDeTapas
  • 516
  • 1
  • 7
  • 16

3 Answers3

2

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
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Well yes they have a supertype but it is not something that I can change since I am using a framework. But I will just create a mutual interface, it will work fine. – PandaDeTapas Jun 11 '15 at 09:33
  • @PandaDeTapas: Yup, there you go. Adding an interface of your own with this in it is [Eran's answer](http://stackoverflow.com/a/30776852/157247), I believe. – T.J. Crowder Jun 11 '15 at 09:36
1

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

Community
  • 1
  • 1
Giovanni
  • 3,951
  • 2
  • 24
  • 30