-2

So guys im trying to access a private Array from another class. Is there a way to access said array without a get-Method for the array?

public class Entity {

 private int key;
 private int value;

 public Entity(int k, int v) {
  key = k;
  value = v;
 }

 public int getKey() {
  return key;
 }

 public int getValue() {
  return value;
 }

 public void setValue(int v) {
  value = v;
 }
 public void setKey(int k) // selbst geadded
 {
  key = k;
 }
}

Those are the elements that are contained in the array.

public class Relation {

 private Entity[] map;

 public Relation(int n) {
  map = new Entity[n]; // größe des neuen feldes
 }

 public int size() {
  return map.length;
 }

 public Entity extract(int i) {
  if (i >= map.length || i < 0 || map[i] != null) {
   return null;
  }


  int key = map[i].getKey();
  int value = map[i].getValue();
  map[i] = null;
  return new Entity(key, value);

 }


 public boolean into(Entity e) {
  for (int i = 0; i < size(); i++) {
   if (map[i] == null) {
    map[i] = e;
    return true;
   }
  }
  return false;
 }

 public static void main(String[] args) {

 }
}

Relation is the Method im supposed to use. This class contains the private array which im trying to access.

public class Use {

 public static boolean substitute(Relation rel, Entity e) {
  if (rel.size() > 0) {
   rel.map[0] = e; // "map has private acccess in Relation"
   return true;
  }
  return false;
 }

 public static Relation eliminate(Relation rel, int k) {
  int counter = 0;
  for (int i = 0; i < rel.size(); i++) {
   if (map[i] != k) // // "cannot find symbol map"
   {
    counter++;
   }
  }
 }
}

And this is the class in which im trying to access the array. The methods here are not finished yet since im getting errors whenever im trying to access the map in the Relation class in any why since I cant figure it out.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
IHunteer
  • 3
  • 1

1 Answers1

0

To access fields, you need a FieldInfo:

Type relationType = typeof(Relation);
FieldInfo fieldRelationMap = relationType.GetField("map",
     BindingFlags.Instance | BindingFlags.NonPublic);

FieldInfo has a GetValue and a SetValue

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116