Java变量类型识别

        使用时如果已经确定变量类型的范围,那么建议使用instanceof。如果不确认变量的范围的话就使用Object.getClass().getName()来得到,而getSimpleName只能得到类名得不到包名这就不能确认这个对象了,毕竟有很多重名的类还需要依靠包名来进行判断的像java.util.Date和java.sql.Date。

实例:

package com.bijian.study;

/**
 * 使用时如果已经确定变量类型的范围,那么建议使用instanceof。
 * 如果不确认变量的范围的话就使用Object.getClass().getName()来得到,而getSimpleName只能得到类名得不到包名这就不能确认这个对象了,
 * 毕竟有很多重名的类还需要依靠包名来进行判断的像java.util.Date和java.sql.Date。
 */
public class JavaTypeTest {
    
    public static void main(String[] args) {
        
        Integer a = new Integer(2);
        TypeObject to = new TypeObject();
        // 1.反射
        System.out.println("to的类型:" + to.getClass().getName());
        System.out.println(int.class.getName());
        System.out.println(Integer.class.getName());
        // 但是对于一个不确定类型的基本数据类型变量我们没法用反射来获取其类型。
        System.out.println("----------------------");

        // 2.instanceof
        if (to instanceof TypeObject) {
            System.out.println("to是TypeObject类型的");
        }
        if (a instanceof Integer) {
            System.out.println("a是int类型的");
        }
        // 但是这种办法貌似也没法确定基本数据类型
        System.out.println("----------------------");
    }
}

// 定义一个类,为了演示引用类型的类型检测
class TypeObject {
}

运行结果:

to的类型:com.bijian.study.TypeObject
int
java.lang.Integer
----------------------
to是TypeObject类型的
a是int类型的
----------------------

参考文章:http://snkcxy.iteye.com/blog/1827913

猜你喜欢

转载自bijian1013.iteye.com/blog/2307189