程序:
public class T {
static boolean tt = true;
static{
if(tt){
throw new RuntimeException("hhh");
}
System.out.println("OK");
}
}
public class B {
public static void main(String[] args) throws Exception {
T t = null;
try{
t = new T();
}catch(Throwable e){
e.printStackTrace();
}
T.tt = false;
t = new T();
}
}
运行B类:
java.lang.ExceptionInInitializerError
at B.main(B.java:9)
Caused by: java.lang.RuntimeException: hhh
at T.
(T.java:10)
... 1 more
Exception in thread "main" java.lang.NoClassDefFoundError
at B.main(B.java:13)
说明:class T在static块中产生了异常,因而T实例创建失败,当再次要创建T实例时就会产生NoClassDefFoundError了。至于更深层次的原因追究有望大家提供。
实际应用中曾犯过这样的错误:
import java.io.PrintStream;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HibernateUtil {
private static Log log = null;
private static Configuration configuration = null;
private static SessionFactory sessionFactory = null;
private static String CONFIG_FILE_LOCATION = null;
public static Session getSession() throws DatastoreException {
try {
return sessionFactory.openSession();
}catch (Exception ex) {
log.error(ex.getMessage());
throw DatastoreException.datastoreError(ex);
}
}
public static void closeSession(Session session) throws DatastoreException {
try {
session.close();
}catch (Exception ex) {
log.error(ex.getMessage());
throw DatastoreException.datastoreError(ex);
}
}
static {
log = LogFactory.getLog(com.vicpol.framework.util.HibernateUtil.class);
CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
try {
System.out.println("---1");
configuration = new Configuration();
System.out.println("---2");
configuration.configure(CONFIG_FILE_LOCATION);
System.out.println("---3");
sessionFactory = configuration.buildSessionFactory();
System.out.println("---4");
}catch (Throwable ex) {
log.error(ex.getMessage());
throw new ExceptionInInitializerError(ex);
}
}
}
避免这种错误的方法:
1、不要static块中抱出异常,static块中抛出的异常会把类定义破坏。
2、使用static块对类进行初始化是不应该被推荐的,替代的方法是写一个静态的init方法,如果初始化失败了也不会把类的定义破坏,不妨碍第二次初始化。