java中如何获得某一变量的类型,如int ,long ,double 型,万分感谢!

boboxing2003 2003-10-18 10:11:38
java中如何获得某一变量的类型,如int ,long ,double 型,万分感谢!
应该可以做到的吧,谢谢!
...全文
904 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
sasa_sasa 2003-10-18
  • 打赏
  • 举报
回复
Integer.ParseInt(String str);
swinging 2003-10-18
  • 打赏
  • 举报
回复
如果是对象,那么可以使用getClass().getName()方法获得该对象的类名,
如果是原数据类型(如int),这些在编译期就强制检验的,要获取类型基本没意义。
当然,还有就是利用反射机制获取原数据类型的,这个时候如果需要确定类型,
同样的,反射机制返回值是对象,比如对于类属性的返回,是Field对象,可以
通过里面的getType().getName()获得该属性的类型名称,下面一个例子:


public class Test {
public int testClass = 0;
public void testClass() {
Object DeclaringClass = null;
Object Type = null;
Object ReturnType = null;
try {
DeclaringClass = new Test().getClass().getDeclaredField("testClass").getDeclaringClass();
Type = new Test().getClass().getDeclaredField("testClass").getType().getName();
ReturnType = new Test().getClass().getMethod("testClass", new Class[]{}).getReturnType();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
System.out.println("=========testClass==========");
System.out.println(DeclaringClass);
System.out.println( "对象属性testClass类型="Type);
System.out.println("方法testClass返回值类型="+ ReturnType);
System.out.println("=========testClass==========");
}

public static void main(String[] args) {
new Test().testClass();
}
}


对于使用反射获取方法的参数类型可以用:new Test().getClass().getMethod("testClass", new Class[]{}).getParameterTypes(),获得一个数组,这个例子没有输入参数,所以就不加进去了。
coolskeeter 2003-10-18
  • 打赏
  • 举报
回复
还是用相应的类吧,那样很容易.
Integer,Long,Double
littlecpu 2003-10-18
  • 打赏
  • 举报
回复
有个简单的方法

class test
{
public static void main(String[] s)
{
System.out.println(test(1));
double d = 1234d;
System.out.println(util.getType(d));
}
}

class util
{
static String getType(boolean b){ return "boolean";};
static String getType(double d){ return "double";};
...
static String getType(short s){ return "short";};
}

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧