对一个未知类型的数据,进行java判断

常见的情况是,我们从mysql读出了数据,批量灌入到HASHMAP里,于是这个HashMap里,有int类型,有string,有boolean,有long

下面的函数,直接判断出数据的类型,方便我们做转义的操作。之前写过一个instanceof 的专门用法。

public static <T> String getType(T t){ 
		if(t instanceof String){ 
		return "string"; 
		}else if(t instanceof Integer){ 
			return "int"; 
		}else if(t instanceof Boolean){
			return "boolean";
		}else{ 
			return " do not know"; 
		}
	}

一般这么用。

Iterator iter = h.entrySet().iterator();
while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				Object key = entry.getKey();
				Object val = entry.getValue();
				String k = (String) key;
				String v = "";
				String t = getType(val);
				if(getType(val).equals("int")){
					Integer I = (Integer)val;
					v = String.valueOf(I.intValue());
				}else if("boolean".equals(t)){
					Boolean b = (Boolean)val;
					if(b) v = "1";
					if(!b) v = "0";
				}
				else{
					 v = (String) val;			
				}
 
				sb.append(k + "=" + v + "&");
			}


This entry was posted in JAVA and tagged , , , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-type/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力

One Response to 对一个未知类型的数据,进行java判断

  1. 才了解点JavaScript的知识….

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

  

About Me

静水流深,水滴石穿