论坛首页 Java企业应用论坛

Class的isAssignableFrom的用法

浏览 2080 次
该帖已经被评为隐藏帖
作者 正文
   发表时间:2009-12-10  
  难用的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));
	}
}
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics