1 /**
2 * Java program to demonstrate how failure of static initialization subsequently cause
3 * java.lang.NoClassDefFoundError in Java.
4 * @author Javin Paul
5 */
6 public class NoClassDefFoundErrorDueToStaticInitFailure {
7
8 public static void main(String args[]){
9
10 List<User> users = new ArrayList<User>(2);
11
12 for(int i=0; i<2; i++){
13 try{
14 users.add(new User(String.valueOf(i))); //will throw NoClassDefFoundError
15 }catch(Throwable t){
16 t.printStackTrace();
17 }
18 }
19 }
20 }
21
22 class User{
23 private static String USER_ID = getUserId();
24
25 public User(String id){
26 this.USER_ID = id;
27 }
28 private static String getUserId() {
29 throw new RuntimeException("UserId Not found");
30 }
31 }
32
33 Output
34 java.lang.ExceptionInInitializerError
35 at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)
36 Caused by: java.lang.RuntimeException: UserId Not found
37 at testing.User.getUserId(NoClassDefFoundErrorDueToStaticInitFailure.java:41)
38 at testing.User.<clinit>(NoClassDefFoundErrorDueToStaticInitFailure.java:35)
39 ... 1 more
40 java.lang.NoClassDefFoundError: Could not initialize class testing.User
41 at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)
42
43
44 Read more: http://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz3dqtbvHDy