Java中Object转换为int类型或String类型

一、判断Object的类型

下面是截取的一个判断Objec的类型,然后给Excel的单元格设置类型和添加值的操作:

obj instanceof 类型
Object obj = entityMap.get(j);
if (obj instanceof Integer) {
     cell.setCellType(Cell.CELL_TYPE_NUMERIC);
     cell.setCellStyle(cellStyleMap.get(j).getCellStyle());
     cell.setCellValue((int) obj);
 } else if (obj instanceof Double) {
     cell.setCellType(Cell.CELL_TYPE_NUMERIC);
     cell.setCellStyle(cellStyleMap.get(j).getCellStyle());
     cell.setCellValue((Double) obj);
 }else 。。。

二、String与int类型相互转换

String转换为int类型的方法:

  • Integer.parseInt([String])
  • Integer.valueOf([String]).intValue();
  • Integer.decode([String]):将 String 解码为 Integer。接受通过以下语法给出的十进制、十六进制和八进制数字

int转换为String类型:

  • String s = String.valueOf(i);
  • String s = Integer.toString(i);
  • String s = “” + i;

三、Object类型转换为int类型

  • 如果object是byte,short,int,char类型生成的,那么不用转换直接赋值就ok了。
  • 如果object是字符串类型生成的,先把object转换为String类型的,再把String类型转换为int类型。

String myInt=”123”;
Object os=myInt;
int b=Integer.parseInt((String)os);//还可以os.toString()
如果object是float,double,long类型生成的,思路和上面一样,先把object转换为相应的数据类型,然后再转换为int类型。


四、Object类型转换为String类型

  • String title=String.valueOf(obj);
  • String content=String.valueOf(obj);

五、Object类型转换为Date类型

SimpleDateFormat sdf=new SimpleDateFormat(“yyyy-mm-dd”);
String indate=sdf.format(date);
Date indate=sdf.parse(String);

猜你喜欢

转载自blog.csdn.net/axela30w/article/details/79923331