Chan Chen Coding...

          Java中的getName(), .class 和forName()的區別

          1. 首先這個函數或屬性都是用來獲得一個類型的Class對象。每一個類型在java虛擬機中都對應一個Class對象,該對象用于java虛擬機加載一個該類型的對象到內存中。
          2. 其次getClass都是用于一個Custom object的,.class用于一個類型(系統封裝或者用戶自定義類型),比如People類型,而forName 是Class類型的一個靜態函數,用于獲得一個類型的Class對象。
          3. getClass返回的Class對象,是在運行時確定的,而另外兩個都是在編譯的時候確定的。

          假如我們有兩個類型People和Student,其中student繼承自People。如果執行下面的代碼:

          People people = new Student();
          try{
              System.out.println(Class.forName("People") == People.class);
              System.out.println(Class.forName("People") == people.getClass());
               
              System.out.println(people.getClass() == People.class);
               
              System.out.println(Class.forName("People"));//People
              System.out.println(people.getClass());//Student
              System.out.println(People.class);//People
          }catch(Exception e)
          {
              e.printStackTrace();
          }
          Student student = new Student();
          try{
              System.out.println(Class.forName("Student") == Student.class);
              System.out.println(Class.forName("Student") == student.getClass());
               
              System.out.println(student.getClass() == Student.class);
               
              System.out.println(Class.forName("Student"));//Student
              System.out.println(student.getClass());//Student
              System.out.println(Student.class);//Student
          }catch(Exception e)
          {
              e.printStackTrace();
          }



          -----------------------------------------------------
          Silence, the way to avoid many problems;
          Smile, the way to solve many problems;

          posted on 2012-11-23 23:09 Chan Chen 閱讀(798) 評論(0)  編輯  收藏 所屬分類: Scala / Java

          主站蜘蛛池模板: 宁陵县| 崇明县| 报价| 镇江市| 炉霍县| 阜新市| 静宁县| 新田县| 赤城县| 孙吴县| 林口县| 当阳市| 招远市| 新田县| 周宁县| 北票市| 承德市| 定边县| 临湘市| 扎兰屯市| 南皮县| 三台县| 克什克腾旗| 比如县| 祁东县| 高雄市| 周宁县| 彰化市| 平阳县| 封开县| 石嘴山市| 南城县| 双流县| 宝坻区| 万载县| 祁门县| 中江县| 四会市| 南漳县| 德安县| 修水县|