转转转!!java基础一些静态代码块等知识点
一、代码块:
构造代码块------类中方法的外面;每次调用构造方法都执行;
静态代码块------类中方法的外面,括号前加上static;只执行一次,随着类的加载而执行;
static代码块、构造代码块,自己写的做实验的小例子:
1 public class TestStatic{ 2 public static void main(String args[]){ 3 TestBlock t1 = new TestBlock(); 4 System.out.println(t1); 5 System.out.println("-------------------------"); 6 7 TestBlock t2 = new TestBlock(50); 8 System.out.println(t2); 9 System.out.println("-------------------------"); 10 11 TestBlock t3 = new TestBlock(11, "lisi"); 12 System.out.println(t3); 13 } 14 } 15 16 class TestBlock{ 17 18 int id = 100; 19 String sex; 20 String name; 21 22 //static block, when the class load, execute it; 23 static { 24 System.out.println("init TestBlock...."); 25 } 26 27 //constructor block, when constructor method execute, this block execute 28 { 29 sex = "male"; 30 name = "zhangsan"; 31 System.out.println("init begin constructor..."); 32 } 33 34 TestBlock(){ 35 36 } 37 38 TestBlock(int id){ 39 this.id = id; 40 } 41 42 TestBlock(int id, String name){ 43 this.id = id; 44 this.name = name; 45 } 46 47 public String toString(){ 48 return "id: " + id + " sex: " + sex + " name:" + name; 49 } 50 51 }
打印结果:
===============================================================================
1 java中的length属性是针对数组说的,比如说你声明了一个数组,想知道这个数组的长度则用到了length这个属性.
2 java中的length()方法是针对字符串String说的,如果想看这个字符串的长度则用到length()这个方法.
3.java中的size()方法是针对泛型集合说的,如果想看这个泛型有多少个元素,就调用此方法来查看!
==================================================================================
类什么时候被加载?
--类用到的时候才被加载;
比如下面一段代码:
public class StudentTest { static{ System.out.println("StudentTest类被加载了."); } private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); //添加学生 private void add(){ System.out.println("add方法开始执行..."); Session session = sessionFactory.openSession(); //生成一个session session.beginTransaction(); //开启事务 Student s = new Student(); s.setName("张三"); session.save(s); session.getTransaction().commit(); //提交事务 session.close(); //关闭session } public static void main(String[] args) { StudentTest studentTest = new StudentTest(); studentTest.add(); } }
我在HibernateUtil.getSessionFactory()方法中把读取hibernate配置文件的代码注释掉了,也读取不到Student的映射文件;
结果打印:
StudentTest类被加载了.
HibernateUtil类被加载了.
add方法开始执行...
Exception in thread "main" java.lang.NullPointerException
at com.cy.service.StudentTest.add(StudentTest.java:23)
at com.cy.service.StudentTest.main(StudentTest.java:36)
main中的方法用到了StudentTest,无疑首先被加载了;
StudentTest中使用到了HibernateUtil类,所以打印HibernateUtil类被加载了;
一直打印了add方法开始执行,都没有打印student类被加载,因为此时student类压根就没有用到!!
===========================================================================================