有没有办法输出java数据类型到控制台? [英] Is there a way to output the java data type to the console?

查看:510
本文介绍了有没有办法输出java数据类型到控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调试我继承的程序。这个程序包含字符串,数组列表和集合,大量的类型之间的转换,我需要做一些String操作( substring 等)

I'm trying to debug a program I inherited. This program contains Strings, array lists and collections, lots of casting between types, and I need to do some String manipulations (substring, etc.)

当打印到控制台时,数据类似Strings [例如,它是一行文本,如 Johnson,John 芝加哥地区),但我的代码错误出来与各种索引超出范围错误,暗示我的代码to cast到String不工作。

The data look like Strings when printed to the console (e.g., it's a line of text, like Johnson, John or Chicago Region), but my code is erroring out with various index out of range errors, suggesting that my code to cast to String isn't working.

我想尝试找出哪些数据类型进入并离开我的方法来验证程序是否按预期方式运行。有什么办法在Java中找到字段类型吗?在一个完美的世界中,我可以在每一步都生成控制台输出,这将给我的数据值,它是一个字符串,数组列表或集合。

I'd like to try to figure out what data types are coming into and leaving my methods to verify that the program is acting as expected. Is there any way to find a field type in Java? In a perfect world, I could generate console output at every step that would give me the data value and whether it's a String, array list, or collection. Can that be done?

推荐答案

给定任何对象的实例,可以调用它的getClass()方法来获取一个实例描述对象类型的Class对象。

Given an instance of any object, you can call it's getClass() method to get an instance of the Class object that describe the type of the object.

使用Class对象,您可以轻松地打印它的类型名称:

Using the Class object, you can easily print it's type name:

Integer number=Integer.valueOf(15);
System.out.println(number.getClass().getName());

这样打印到控制台类的完全限定名称,例如:

This print to console the fully qualified name of the class, which for the example is:

java.lang.Integer

如果你想要一个更简洁的输出,你可以改用:

If you want a more concise output, you can use instead:

Integer number=Integer.valueOf(15);
System.out.println(number.getClass().getSimpleName());

getSimpleName()只提供类的名称:

getSimpleName() give you only the name of the class:

Integer

打印原始类型变量有点复杂:请参见此SO问题

Printing the type of primitive variables is a bit more complex: see this SO question for details.

这篇关于有没有办法输出java数据类型到控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆