Method calls inside a Java class

前端 未结 8 2336
难免孤独
难免孤独 2020-11-28 15:31

I was setting out to write a piece of code today in Eclipse, and I started out like so:

public class MyClass {
    System.currentTimeMillis();
}
         


        
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 16:20

    Try this way:

    public class MyClass {
        static {
            System.currentTimeMillis();
        }
    }
    

    If you call System.currentTimeMillis() inside a static statement it works. The static block will be called when the class "MyClass" is loaded by the class loader.

提交回复
热议问题