Java教程

JavaSE:反射机制 - 获取其他结构信息

本文主要是介绍JavaSE:反射机制 - 获取其他结构信息,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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 }

 

这篇关于JavaSE:反射机制 - 获取其他结构信息的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!