mercredi 8 août 2018

How to access field inherited from an abstract class with Reflection?

So I have an abstract Geo class that represents 3D geometric shapes, so it has inherited fields such as Vector positions and abstract methods, like update and display.

Since my Cube class inherits from this Geo class, I don't re-declare my fields, and I just set them in the constructor for the Cube class. I didn't get an error originally when I didn't inherit from Geo and declared the fields in the Cube class.

However, I noticed when I try to see if the Field exists it throws this error:

java.lang.NoSuchFieldException: boundBox

This is the Reflection code that checks for the field (the object is a Cube object):

try {
   Field field = object.getClass().getDeclaredField("boundBox");
} catch(Exception e){
   e.printStackTrace();
}

So again, I don't re-declare the "boundBox" field, because I already declared it in the Geo abstract class. Here's the basic portion of my abstract class and child class:

abstract class Geo {
  public Vector pos;
  public BoundingBox boundBox;

  abstract void update();
  abstract void display();
}

class Cube extends Geo {
  public Cube(Vector pos, float dim){
    this.pos = pos; 
    boundBox = new BoundingBox(pos,dim);
  }
  @Override
  void update(){
  }
  @Override
  void display(){
  }
}





Aucun commentaire:

Enregistrer un commentaire