Java.lang.NullPointerException is thrown

Class.forName("Essence.Users"); Users.AllUsers.printer(); // Выбрасывается в этой строке. 

Here is the Users class.

 public class Users { public static Users AllUsers; private ArrayList <UserThread> Users; public void printer() { System.out.print("xxxxxx"); } private Users() { System.out.print("Обьект создался."); Users = new ArrayList <UserThread>(); } static { Users AllUsers = new Users(); } } 
  • And "The object was created." is displayed? - VladD
  • @ Kitty, return the answer, it was correct :) - VladD
  • @VladD Yes, I also thought to check what the conditions for calling static in the standard, but, in general, okay :) - Costantino Rupert
  • As far as I remember, the static block is called no later than the first call to any field / method of the class, be it static or not. Not sure about reflection. - VladD
  • one
    @ Kitty: found a place in the specification : section 12.4.1. Reflection has also been included in the list:> java.lang.reflect . - VladD


1 answer 1

  • You created a local AllUsers variable of type Users in your static constructor, and you did not initialize the corresponding field of the Users class.

Apparently, the following was meant: static { AllUsers = new Users() }

  • Class.forName is completely unnecessary here - a static constructor is called when creating an instance of a class or trying to access static fields of a class.
  • You are right!) Thank you. Inattention is dangerous. - alex91