Java编译能通过,但是运行的时候提示有错误。
提示出现这样的错误:
Exception in thread "main" java.lang.ExceptionInInitializerError at org.idea.ok.Person.main(Person.java:32) Caused by: java.lang.NullPointerException at org.idea.ok.Gender1.<init>(Gender1.java:28) at org.idea.ok.Gender1.<clinit>(Gender1.java:17) ... 1 more
原程序如下:
package org.idea.ok; /* *枚举类 *既可以通过public访问权限的静态常量来访问实例; *也可以通过Gender1类的getInstance静态方法来访问实例变量。 */ import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.NoSuchElementException; import java.util.Map; import java.util.HashMap; public class Gender1 implements Serializable { public static final Gender1 FEMALE = new Gender1(new Character('F'), "FEMALE"); public static final Gender1 MALE = new Gender1(new Character('M'), "MALE"); private final Character sex; private final transient String description; private static Map<Character, Gender1> instancesBySex = new HashMap<Character, Gender1>(); private Gender1(Character sex, String description) { this.sex = sex; this.description = description; instancesBySex.put(sex, this); } public Character getSex() { return sex; } public String getDescription() { return description; } public static Collection getAllValues() { return Collections.unmodifiableCollection(instancesBySex.values()); } public static Gender1 getInstance(Character sex) { /*按照参数指定的性别缩写查找Gender1实例*/ Gender1 result = (Gender1)instancesBySex.get(sex); if (result == null) { throw new NoSuchElementException(sex.toString()); } return result; } public String toString() { return description; } private Object readResolve() { /*保证反序列化时直接返回Gender1类包含的静态实例*/ return getInstance(sex); } }
package org.idea.ok; /* */ public class Person { private String name; private Gender1 gender; public Person(String name, Gender1 gender) { this.name = name; this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Gender1 getGender() { return gender; } public void setGender(Gender1 gender) { this.gender = gender; } public static void main(String[] args) { Person mary = new Person("Mary", Gender1.FEMALE); System.out.println("name = " + mary.getName() + "\t" + "gender = " + mary.getGender()); } }
程序异常提示是:初始化的时候错误;但是造成这种异常的根源是Gender1中的代码的问题。这个我还真是找不出来了,麻烦谁能找出来的,小弟不胜感谢。