java 判断是否是基本类型_Java中怎样判断一个变量是否属于哪种类型

展开全部

变量类型636f707962616964757a686964616f31333361306437识别有3种方法:

1、通过反射拿到变量的类型;

2、instanceof关键字判断;

3、通过java的多态(方法重载)来DIY类型识别。

举例如下:package com.cxyapi.oo;

/** 类型识别工具测试类

* @author cxy @ www.cxyapi.com

*/

public class TypeToolsTest

{

public static void main(String[] args)

{

int i=0;

TypeObject to=new TypeObject();

//1.反射

System.out.println("to的类型:"+to.getClass().getSimpleName());

System.out.println(int.class.getSimpleName());

System.out.println(Integer.class.getSimpleName());

//但是对于一个不确定类型的基本数据类型变量我们没法用反射来获取其类型。

System.out.println("----------------------");

//2.instanceof

if(to instanceof TypeObject){ System.out.println("to是TypeObject类型的");}

//但是这种办法貌似也没法确定基本数据类型

System.out.println("----------------------");

//以上两种方式对于对象,引用类型的都很好用,但是对基本数据类型就不那么好用了。

//3.通过多态(方法的重载)

System.out.println("i是:"+TypeTools.getType(i));

System.out.println("to是:"+TypeTools.getType(to));

System.out.println("\"cxyapi\"是:"+TypeTools.getType("www.cxyapi.com"));

//可以看出来 最后一种方式使用多态的方式达到了检测类型(基本类型和引用类型)的目的

//除了弥补其他两种方式不能检测基本数据类型的不足在外,还能自己DIY类型信息

}

}

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

class TypeObject{}

自定义的类型识别工具:package com.cxyapi.oo;

import java.util.HashMap;

import java.util.Map;

/** 类型识别工具

* @author cxy @ www.cxyapi.com

*/

public class TypeTools

{

//获得类型

public static Map getType(Object o)

{

Map typeInfo=new HashMap();

typeInfo.put("类型", o.getClass().getSimpleName());

typeInfo.put("描述", "引用类型");

return typeInfo;

}

public static Map getType(int i)

{

Map typeInfo=new HashMap();

typeInfo.put("类型", "int");

typeInfo.put("描述", "整形");

return typeInfo;

}

public static Map getType(long l)

{

Map typeInfo=new HashMap();

typeInfo.put("类型", "long");

typeInfo.put("描述", "长整型");

return typeInfo;

}

public static Map getType(boolean b)

{

Map typeInfo=new HashMap();

typeInfo.put("类型", "boolean");

typeInfo.put("描述", "布尔类型");

return typeInfo;

}

public static Map getType(char b)

{

Map typeInfo=new HashMap();

typeInfo.put("类型", "char");

typeInfo.put("描述", "字符");

return typeInfo;

}

public static Map getType(float f)

{

Map typeInfo=new HashMap();

typeInfo.put("类型", "float");

typeInfo.put("描述", "单精度浮点型");

return typeInfo;

}

public static Map getType(double d)

{

Map typeInfo=new HashMap();

typeInfo.put("类型", "double");

typeInfo.put("描述", "双精度浮点型");

return typeInfo;

}

public static Map getType(String s)

{

Map typeInfo=new HashMap();

typeInfo.put("类型", "String");

typeInfo.put("描述", "字符串类型");

return typeInfo;

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值