1.
Package getPackage() | 获取所在的包信息 |
Class<? super T>getSuperclass() | 获取继承的父类信息 |
Class<?>[] getInterfaces() | 获取实现的所有接口 |
Annotation[] getAnnotations() | 获取注解信息 |
Type[] getGenericInterface() | 获取泛型信息 |
2. 代码示例
1 import java.io.Serializable; 2 3 @MyAnnotation 4 public class Student<T, E> extends Person implements Comparable<String>, Serializable { 5 6 @Override 7 public int compareTo(String o) { 8 return 0; 9 } 10 }
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 }
运行效果
3. 反射机制 - 小结
4.反射机制 - 练习