反射--获取构造器,获取父类,获取带泛型的父类,获取实现的接口,获取所在的包,获取注解
反射的应用
1.获取构造器
代码
public void test2() throws Exception{
String className="test.Person";
Class clazz=Class.forName(className);
Constructor[] cons=clazz.getDeclaredConstructors();
for(Constructor c:cons){
System.out.println(c);
}
}
运行结果
2.获取父类
代码
public void Test1(){
Class clazz=Person.class;
Class superclass =clazz.getSuperclass();
System.out.println(superclass);
}
运行结果
3.获取带泛型的父类
代码
public void Test2(){
Class clazz=Person.class;
Type type1 =clazz.getGenericSuperclass();
System.out.println(type1);
}
运行结果
4.获取父类的泛型
代码
public void Test3(){
Class clazz=Person.class;
Type type1 =clazz.getGenericSuperclass();
ParameterizedType param=(ParameterizedType)type1;
Type[] ars=param.getActualTypeArguments();
System.out.println(((Class) ars[0]).getName());
}
运行结果
5.获取实现的接口
代码
public void Test4(){
Class clazz=Person.class;
Class[] interfaces =clazz.getInterfaces();
for(Class i:interfaces){
System.out.println(i);
}
}
运行结果
6.获取所在的包
代码
public void Test5(){
Class clazz=Person.class;
Package pack =clazz.getPackage();
System.out.println(pack);
}
运行结果
7.获取注解
代码
public void Test6(){
Class clazz=Person.class;
Annotation[] anns=clazz.getAnnotations();
for(Annotation a:anns){
System.out.println(a);
}
}
运行结果
《爆裂鼓手》