¿Hay alguna forma de enviar el tipo de datos java a la consola?

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.)

Los datos vea 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.

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?

preguntado el 03 de mayo de 12 a las 20:05

By the way, if you're not getting a ClassCastException, then the cast to String is trabajando. -

5 Respuestas

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.

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() give you only the name of the class:

Integer

Printing the type of primitive variables is a bit more complex: see esta pregunta SO para más detalles.

contestado el 23 de mayo de 17 a las 12:05

For any object x, you could print x.getClass().

contestado el 03 de mayo de 12 a las 20:05

I would do x.getClass.getName() - colin d

@PaulVargas if(object == null){ sout("null")} - turba

And what about arrays? Arrays of objects or primitives? - Pablo Vargas

Una variedad de ints will print [I, por ejemplo. - Keith Randall

instance.getClass() is the way to go if you just want to print the type. You can also use instanceof if you want to branch the behaviour based on type e.g.

if ( x instanceof String )
{
   // handle string
}

contestado el 03 de mayo de 12 a las 21:05

Utilice el getClass() método.

Object o;
System.out.println(o.getClass());

contestado el 03 de mayo de 12 a las 21:05

Solo haz .class.getName(); in any object

contestado el 03 de mayo de 12 a las 21:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.