在java中 如何获取变量的类型?
java中获取变量的类型可以使用每个类型的getClass()方法来获得,示例如下:
class Test
{
public static void main(String[] args)
{
int i=1; //int类型变量
System.out.println(getType(i)); //打印变量类型为int
}
public static String getType(Object o){ //获取变量类型方法
return o.getClass().toString(); //使用int类型的getClass()方法
}
}
2013-08-02
public class Test15 {
public static void main(String[] args)
{
int i=1;
Integer i1 = 2;
double d = 1.8;
long l = 76;
boolean b = false;
System.out.println(getType(i));
System.out.println(getType(i1));
System.out.println(getType(d));
System.out.println(getType(l));
System.out.println(getType(b));
}
public static String getType(Object o){
return o.getClass().toString();
}
public static String getType(int o){
return "int";
}
public static String getType(byte o){
return "byte";
}
public static String getType(char o){
return "char";
}
public static String getType(double o){
return "double";
}
public static String getType(float o){
return "float";
}
public static String getType(long o){
return "long";
}
public static String getType(boolean o){
return "boolean";
}
public static String getType(short o){
return "short";
}
}