日期:2014-05-20  浏览次数:20746 次

在JAVA中如何取得一个变量的类型?
希望可以通过变量知道它的类型,特别是基本数据类型变量的类型,不知道有没有办法?

------解决方案--------------------
class Test
{
public static void main(String[] args)
{
int i=1;
System.out.println(getType(i));
}
public static String getType(Object o){
return o.getClass().toString();
}
}
------解决方案--------------------
受点累给1楼的加点东西...

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 ";
}
}