+ 3

From java. How to find a datatype of a variable at run time?

there is a variable in java program. at run time I need to find the type of variable. can anyone put lights on this?

5th Feb 2018, 4:45 PM
Magesh Santhamani
Magesh Santhamani - avatar
2 ответов
+ 7
you can use instanceof, as in: if (obj instanceof myclass) { ... } But you have to be specify the classes or datatypes to test.
5th Feb 2018, 4:55 PM
Eric Blinkidu
Eric Blinkidu - avatar
+ 6
Using the code below, it'll tell you which type it is, including primitive types. This works out best because it doesn't return a boolean value and instead returns the actual data type name. Syntax: ((Object)YOURVARIABLEHERE).getClass().getSimpleName() https://code.sololearn.com/cnf9PQK7t1YW/#java public class Program { public static void main(String[] args) { String phrase = "Have a nice day!"; int number = 1; float decimal = 1f; System.out.print(phrase + " ["); System.out.println(((Object)phrase).getClass().getSimpleName() + "]"); System.out.print(number + " ["); System.out.println(((Object)number).getClass().getSimpleName() + "]"); System.out.print(decimal + " ["); System.out.println(((Object)decimal).getClass().getSimpleName() + "]"); } } // OUTPUT:::: Have a nice day! [String] 1 [Integer] 1.0 [Float]
5th Feb 2018, 5:30 PM
Fata1 Err0r
Fata1 Err0r - avatar