反射

 
3
4
5
6
7
8
package  net.xsoftlab.baike;
public  class  TestReflect {
     public  static  void  main(String[] args)  throws  Exception {
         TestReflect testReflect =  new  TestReflect();
         System.out.println(testReflect.getClass().getName());
         // 結果 net.xsoftlab.baike.TestReflect
     }
}
package  net.xsoftlab.baike;
public  class  TestReflect {
     public  static  void  main(String[] args)  throws  Exception {
         Class<?> class1 =  null ;
         Class<?> class2 =  null ;
         Class<?> class3 =  null ;
         // 通常採用這種形式
         class1 = Class.forName( "net.xsoftlab.baike.TestReflect" );
         class2 =  new  TestReflect().getClass();
         class3 = TestReflect. class ;
         System.out.println( "類名稱   "  + class1.getName());
         System.out.println( "類名稱   "  + class2.getName());
         System.out.println( "類名稱   "  + class3.getName());
     }
}
 
 
package  net.xsoftlab.baike;
import  java.io.Serializable;
public  class  TestReflect  implements  Serializable {
     private  static  final  long  serialVersionUID = -2862585049955236662L;
     public  static  void  main(String[] args)  throws  Exception {
         Class<?> clazz = Class.forName( "net.xsoftlab.baike.TestReflect" );
         // 取得父類
         Class<?> parentClass = clazz.getSuperclass();
         System.out.println( "clazz的父類爲:"  + parentClass.getName());
         // clazz的父類爲: java.lang.Object
         // 獲取全部的接口
         Class<?> intes[] = clazz.getInterfaces();
         System.out.println( "clazz實現的接口有:" );
         for  ( int  i =  0 ; i < intes.length; i++) {
             System.out.println((i +  1 ) +  ":"  + intes[i].getName());
         }
         // clazz實現的接口有:
         // 1:java.io.Serializable
     }
}
相關文章
相關標籤/搜索