变量类型识别有3种方法:
- 通过反射拿到变量的类型
- instanceof关键字判断
- 通过java的多态(方法重载)来DIY类型识别
具体看例子吧,尤其第三种方式 有一个自定义的TypeTools,我觉得很实用。希望大家喜欢~
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<String,String> getType(Object o)
{
Map<String,String> typeInfo=new HashMap<String,String>();
typeInfo.put("类型", o.getClass().getSimpleName());
typeInfo.put("描述", "引用类型");
return typeInfo;
}
public static Map<String,String> getType(int i)
{
Map<String,String> typeInfo=new HashMap<String,String>();
typeInfo.put("类型", "int");
typeInfo.put("描述", "整形");
return typeInfo;
}
public static Map<String,String> getType(long l)
{
Map<String,String> typeInfo=new HashMap<String,String>();
typeInfo.put("类型", "long");
typeInfo.put("描述", "长整型");
return typeInfo;
}
public static Map<String,String> getType(boolean b)
{
Map<String,String> typeInfo=new HashMap<String,String>();
typeInfo.put("类型", "boolean");
typeInfo.put("描述", "布尔类型");
return typeInfo;
}
public static Map<String,String> getType(char b)
{
Map<String,String> typeInfo=new HashMap<String,String>();
typeInfo.put("类型", "char");
typeInfo.put("描述", "字符");
return typeInfo;
}
public static Map<String,String> getType(float f)
{
Map<String,String> typeInfo=new HashMap<String,String>();
typeInfo.put("类型", "float");
typeInfo.put("描述", "单精度浮点型");
return typeInfo;
}
public static Map<String,String> getType(double d)
{
Map<String,String> typeInfo=new HashMap<String,String>();
typeInfo.put("类型", "double");
typeInfo.put("描述", "双精度浮点型");
return typeInfo;
}
public static Map<String,String> getType(String s)
{
Map<String,String> typeInfo=new HashMap<String,String>();
typeInfo.put("类型", "String");
typeInfo.put("描述", "字符串类型");
return typeInfo;
}
}
声明:
1.原创文章,转载请标明并加本文连接。
2.文章反映个人愚见,如有异议欢迎讨论指正
3.更多的内容请看我的 个人博客(测试版)