JavaSE:反射機制 - 獲取其他結構資訊
阿新 • • 發佈:2021-06-16
1.
Package getPackage() | 獲取所在的包資訊 |
Class<? super T>getSuperclass() | 獲取繼承的父類資訊 |
Class<?>[] getInterfaces() | 獲取實現的所有介面 |
Annotation[] getAnnotations() | 獲取註解資訊 |
Type[] getGenericInterface() | 獲取泛型資訊 |
2. 程式碼示例
1 @Retention(RetentionPolicy.RUNTIME) 2 public @interface MyAnnotation { 3 }
1 public class StudentTest { 2 3 public static void main(String[] args) throws Exception { 4 5 // 獲取Student型別的Class物件 6 Class c1 = Class.forName("com.lagou.task20.Student"); 7 System.out.println("獲取到的包資訊是:" + c1.getPackage()); 8 System.out.println("獲取到的父類資訊是:" + c1.getSuperclass());9 10 System.out.println("-------------------------------------------------"); 11 System.out.println("獲取到的介面資訊是:"); 12 Class[] interfaces = c1.getInterfaces(); 13 for (Class ct : interfaces) { 14 System.out.print(ct + " "); 15 } 16 System.out.println();17 18 System.out.println("-------------------------------------------------"); 19 System.out.println("獲取到的註解資訊是:"); 20 Annotation[] annotations = c1.getAnnotations(); 21 for (Annotation at : annotations) { 22 System.out.print(at + " "); 23 } 24 System.out.println(); 25 26 System.out.println("-------------------------------------------------"); 27 System.out.println("獲取到的泛型資訊是:"); 28 Type[] genericInterfaces = c1.getGenericInterfaces(); 29 for (Type tt : genericInterfaces) { 30 System.out.print(tt + " "); 31 } 32 System.out.println(); 33 } 34 }