Class的isAssignableFrom的用法------>判断2个类是否继承关系[实现]

难用的isAssignableFrom,今天要判断两个类是不是存在父子关系,
首先我们会想到用instanceof去判断,但是有可能是两个接口去比较,
我们用instanceof肯定不行了。后来想到了可爱的Class对象,它里面
提供了一些我们很常见的功能,我的代码是这么写的:

public class AssingableTest {  
    public static void main(String[] args) {  
        Class<?> parent = java.io.InputStream.class;  
        Class<?> child = java.io.FileInputStream.class;  
        System.out.println(child.isAssignableFrom(parent));  
    }  
} 

后来发现出错了,我看了一下javadoc,它是这么写的:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion. See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.

所以我只能修改代码了,我感觉这个方法的命名有问题,程序修改如下就可以了:

public class AssingableTest {  
    public static void main(String[] args) {  
        Class<?> parent = java.io.InputStream.class;  
        Class<?> child = java.io.FileInputStream.class;  
        System.out.println(parent.isAssignableFrom(child));  
    }  
}  
----------------------------------------------------->

基于泛型引发的思考

  ServiceDataFlowListener listener = ApplicationContextFactory.getBean(listenerBeanName, ServiceDataFlowListener.class);
public static <T> T getBean(String listenerBeanName, Class<T> clazz) {
        Object bean = applicationContext.getBean(listenerBeanName);
        if (!ObjectUtils.isEmpty(bean) && clazz.isAssignableFrom(bean.getClass()))
            return (T) bean;
        return null;
    }
``‘
此时我传入ServiceDataFlowListener.class 他的返回值就必须是 ServiceDataFlowListener的实现类
呢么 泛型的写法 <T><----------标注入参和返回值

// https://www.cnblogs.com/zhima-hu/p/7352555.html  详情看大佬的博客
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值