反射(四)------类的其它获取

除了属性,方法外还有其他的一些东西也值得关注,比如构造函数、运行时父类,所属的包、接口和注解等;

测试代码

主体部分参看反射(二)

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);
        }
    }
}

运行结果

709915-20190111152704516-1710974116.png

转载于:https://www.cnblogs.com/SnailsRunning/p/10255358.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值