java - How do I avoid problems arising from accessing static fields before the class is initialized? -
i have code:
public abstract class person { public static final class guy extends person { public static final guy tom = new guy(); public static final guy dick = new guy(); public static final guy harry = new guy(); } public static final list<guy> guys = immutablelist.of(guy.tom, guy.dick, guy.harry); }
i know, looks should enum, , be, needs inherit person, abstract class.
my problem is: if try access list of guys, i'm okay. try access 1 guy in particular, have problem: guy
gets loaded before person
. however, since guy
inherits person
, person
gets loaded, , tries access tom
, since guy
being loaded, can't start load again, , have null reference. (and immutablelist
doesn't accept null, exception.)
so know why happening, i'm not sure how avoid it. move list guy
class, i'll have more 1 implementation of person
, , i'd have master list of person
s in person
class.
it seems strange me it's possible load static inner class without loading containing class, guess makes sense. there way solve problem?
you keep immutable list in separate class, people.guys
:
public class people { public static final list<guy> guys = immutablelist.of(guy.tom, guy.dick, guy.harry); }
this way can still keep individual guys in guy
class:
public abstract class person { public static final class guy extends person { public static final guy tom = new guy(); public static final guy dick = new guy(); public static final guy harry = new guy(); } }
Comments
Post a Comment