• Post Reply Bookmark Topic Watch Topic
  • New Topic

Dynamically determine variable's data type

 
Kajol Singh
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Could someone help me with this issue:
How can I dynamically dtermine if a variable is of type String or String[].
Thanks,
kaj
 
Asanka Nanayakkara
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi.
i got this output after running following piece of code.
String sVariable = new String("Test");
String sArray[] = new String[3];
System.out.println(sVariable.getClass());
System.out.println(sArray.getClass());
//--------------------------------------
The output was
//--------------------------------------
class java.lang.String
class [Ljava.lang.String;
Asanka
 
James Carman
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Kajol Singh:
Hello,
Could someone help me with this issue:
How can I dynamically dtermine if a variable is of type String or String[].
Thanks,
kaj

Suppose we have an object reference "a". You can ask if a.getClass().isArray(). If it is, you can also determine the type of array, by using a.getClass().getComponentType(). Hope this helps.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you could just say
boolean isString = a instanceof String;
boolean isStringArray = a instanceof String[];
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!