当一个对象在创建之前使用类静态实例时,我遇到了这个问题。例如:
class Chair {
public static Chair mychair = new Chair();
public void foo() {}
}
class Table {
public Table() {
Chair.mychair.foo();
}
}
所以如果我调用mychair.foo(),我会得到一个NullPointerException。我知道,在真正需要课程之前,甚至不会执行静态操作。但是我如何强制Java实际加载类,因此它将被创建?
原始程序的Stacktrace:
Exception in thread "main" java.lang.ExceptionInInitializerError
at hu.intelligames.game.level.Level.<init>(Level.java:34)
at hu.intelligames.game.Game.initialize(Game.java:64)
at hu.intelligames.game.Game.<init>(Game.java:43)
at hu.intelligames.game.Game.main(Game.java:80)
Caused by: java.lang.NullPointerException
at hu.intelligames.game.level.tiles.Tile.<clinit>(Tile.java:25)
... 4 more
Level类的构造函数(来自第25行):
public Level(int width, int height) {
this.width = width;
this.height = height;
tiles = new Tile[width * height];
for (int i = 0; i < tiles.length; i++) {
if (i % 3 == 0)
tiles[i] = Tile.GRASS;
else if (i % 3 == 1)
tiles[i] = Tile.GRASS;
else
tiles[i] = Tile.STONE;
}
init();
}
Tile类的整个代码:
public class Tile {
public static Spritesheet tileSheet = new Spritesheet("/tiles.png");
public static final Tile VOID = new Tile(0, 0, tileSheet, 0x00000000);
public static final Tile GRASS = new Tile(1, 0, tileSheet, 0xff00ff00);
public static final Tile STONE = new Tile(2, 0, tileSheet, 0xffaaaaaa);
public static final Tile ROAD = new Tile(3, 0, tileSheet, 0xffabcdef);
private Spritesheet sheet;
private int x;
private int y;
private int colorCode;
private static ArrayList<Tile> tileList;
static {
tileList.add(VOID);
tileList.add(GRASS);
tileList.add(STONE);
tileList.add(ROAD);
}
public Tile(int x, int y, Spritesheet sheet, int colorCode) {
this.sheet = sheet;
this.x = x;
this.y = y;
this.colorCode = colorCode;
}
public void render(int xPos, int yPos, int xOff, int yOff, Screen screen) {
screen.render(xPos, yPos, xOff, yOff, x, y, sheet);
}
public int getColorCode() {
return colorCode;
}
public static Tile getTileByColorCode(int code) {
for (Tile t : tileList) {
if (t.getColorCode() == code) return t;
break;
}
return VOID;
}
}
答案 0 :(得分:1)
private static ArrayList<Tile> tileList;
保持无效
static {
tileList = new ArrayList<>();
tileList.add(VOID);
tileList.add(GRASS);
tileList.add(STONE);
tileList.add(ROAD);
}
答案 1 :(得分:1)
您的字段tileList
未初始化,因此静态初始化代码会抛出NPE。
这应该可以解决问题:
private static ArrayList<Tile> tileList = new ArrayList<>();