难用的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 详情看大佬的博客