I want to get a value from the user. The entered value may belong to any class. After getting the input, I would want to check its datatype. Not providing any restriction to the type of data the user should enter. For example, if he enters 4.56, the output should be float, if he enters "random", the output should be java.lang.String etc. Is it possible to write such a method in Java?
Asked
Active
Viewed 59 times
0
-
2yes, but it 'll be a bit messy. for instance: 4 can be a String, an int, a short, ... so how will you decide? – Stultuske Nov 05 '15 at 10:51
-
Even if you manage this, what do you do of that value afterwards? – fge Nov 05 '15 at 10:53
-
Do you need to consider i18n? i.e. in Germany you use the comma as decimal separator, so the user would enter 4,56. – Ralf Wagner Nov 05 '15 at 10:55
-
Hmmmm interesting, just as an idea to begin with...I would develop something using generics and then hardcode checks using `regex` or parse methods like `Integer.ParseInt()`. – Mustafa sabir Nov 05 '15 at 11:05
1 Answers
0
variable.getClass().getName()
will get you the type of value of the variable.
if you want to validate, you can use instanceof
if(variable instanceof String){}
There is also variable.getClass().getSimpleName()
to get the name of type

notrai
- 696
- 1
- 5
- 15
-
The user wants to check the datatype of value entered by the user. Your solution assumes that the user entered the value, which got stored in the correct variable type (like if user entered 9.51 it got stored in float) and then you are reading that variable's type. – Mustafa sabir Nov 05 '15 at 11:01