0

Is it possible to get the data type of an input variable (could be any primitive type, int, bool, float, double) returned as a string by using just one line of code? I know this can easily be done for a String type using getName and getShortName but I am unsure of how to use these methods to return the type of a primitive type. I also want to keep my code very short for doing this preferably using just one line.

I have searched around and cannot find anywhere this question has been answered in the way I require.

4
  • What do you mean by "an input variable"? It would really help if you could post a complete example of what you're trying to achieve, with an appropriate magicMethod call or whatever to represent the bit you don't know how to do. Commented May 7, 2015 at 12:48
  • I'm not sure you can, but wouldn't you always know this at compile time anyway? Since a primitive isn't an object there's no ambiguity, it must be whatever the declared type is? Commented May 7, 2015 at 12:48
  • Not sure why you want to do this but you can not do this for primitive types. If possible you can use corresponding wrapper types. Commented May 7, 2015 at 12:49
  • Maybe this answer on SO to a similar topic does-int-class-equal-integer-class-or-integer-type-in-java does help. Commented May 7, 2015 at 13:16

1 Answer 1

1

What about Class.getName()?

Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String. If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification, Second Edition.

If this class object represents a primitive type or void, then the name returned is a String equal to the Java language keyword corresponding to the primitive type or void.

You can follow this link in the Java Doc that explain very well how to use this method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.