如何从另一个类访问没有getter方法的私有数组? [重复]

问题描述 投票:-2回答:1

这个问题在这里已有答案:

所以我们试图从另一个类访问私有数组。有没有办法在没有数组的get-Method的情况下访问所述数组?

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;
 }
}

这些是数组中包含的元素。

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

 }
}

关系是我应该使用的方法。该类包含我试图访问的私有数组。

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++;
   }
  }
 }
}

这是我尝试访问数组的类。这里的方法还没有完成,因为即使我试图访问map类中的Relation时出现错误,因为我无法解决这个问题。

java arrays private
1个回答
0
投票

要访问字段,您需要一个FieldInfo

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

FieldInfo有一个GetValue和一个SetValue

© www.soinside.com 2019 - 2024. All rights reserved.