java 判断类和实例的关系(instanceof,isInstance,isAssignableFrom)

判断类与实例的关系有以下三种方式 

1、instanceOf关键字,用来判断对象是否是类的实例 
2、isAssignableFrom,用来判断类型间是否存在派生关系 
3、isInstance方法,用来判断对象是否属于某个类型的实例 

 

        //use instanceOf,用来判断对象是否是类的实例
        System.out.println(new A() instanceof B);//类型比较

        //use isAssignableFrom(),用来判断类型间是否有继承关系

        System.out.println(B.class.isAssignableFrom(A.class));
 
        //use isInstance(),用来判断对象是否是类的实例

        System.out.println(A.class.isInstance(new A()));//class比较

 

import java.util.Date;

public class Program
{
    public static void main(String[] args)
    {
        // Get the Class object associated with Integer.
        Class intClass = Integer.class;

        // Create various objects.
        String str = "Hello";
        Date date = new Date();
        Integer i = new Integer(10);

        // Is str an instance of class Integer?
        boolean check1 = intClass.isInstance(str);
        System.out.println("str is an Integer? " + check1);

        // Is date an instance of class Integer?
        boolean check2 = intClass.isInstance(date);
        System.out.println("date is an Integer? " + check2);

        // Is i an instance of class Integer?
        boolean check3 = intClass.isInstance(i);
        System.out.println("i is an Integer? " + check3);
    }
}

/*
Output:
str is an Integer? false
date is an Integer? false
i is an Integer? true
*/

 

 

posted @ 2012-05-08 20:17  feiling  阅读(10423)  评论(0编辑  收藏  举报