除了属性,方法外还有其他的一些东西也值得关注,比如构造函数、运行时父类,所属的包、接口和注解等;
测试代码
主体部分参看反射(二)
package day19;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.junit.Test;
public class TestOther {
@Test
public void method1() throws ClassNotFoundException {
Class clazz = Class.forName("day19.Person");
System.out.println("----------------------------构造器------------------------");
//该类所有public权限的构造函数(不显示父类的),这里要和属性以及方法区分;
Constructor[] cons1 = clazz.getConstructors();
for(Constructor c:cons1) {
System.out.println(c);
}
//该类所有public、protected、默认的和private修饰的构造函数
Constructor[] cons2 = clazz.getDeclaredConstructors();
for(Constructor c:cons2) {
System.out.println(c);
}
System.out.println("----------------------------运行时父类(不带泛型的)------------------------");
Class superclass1 = clazz.getSuperclass();
System.out.println(superclass1);
System.out.println("----------------------------运行时父类(带泛型的)------------------------");
Type type1= clazz.getGenericSuperclass();
System.out.println(type1);
System.out.println("----------------------------运行时父类的泛型------------------------");
//Type和ParameterizedType都是接口,ParameterizedType是Type的子接口;
ParameterizedType parameterizedType = (ParameterizedType)type1;
Type[] type2 = parameterizedType.getActualTypeArguments();
for(Type type:type2) {
System.out.println(type);
}
System.out.println("----------------------------获取实现的接口(直接实现的,父接口继承的接口不包括在内)------------------------");
Class[] interfaces = clazz.getInterfaces();
for(Class c:interfaces) {
System.out.println(c);
}
System.out.println("----------------------------获取所在的包------------------------");
Package p =clazz.getPackage();
System.out.println(p);
System.out.println("----------------------------获取注解(这里和注解的生命周期有关)------------------------");
Annotation[] annotations = clazz.getAnnotations();
for(Annotation a:annotations) {
System.out.println(a);
}
}
}