1 Reply Latest reply on Sep 11, 2007 11:26 AM by Grizzly9279

    Determining variable type at runtime

    jhandfield Level 1
      So, I know about all the Is functions (e.g. IsArray, IsStruct, IsXML, etc.) but what I can't find is any CFML function that I can feed in a variable and have it spit out what the object's type is.

      I'm currently developing an application which, as part of its error handling, would like to be helpful to the user / folks working with this CFC in that if the data type of an input parameter isn't what it needs it to be (in this specific case, an XML document object) that as part of the detail of the error message it can explicitly tell the user "I needed this variable to be of type X, but you gave me one of type Y (you dummy.)"

      I suppose the simple answer is a UDF that just runs the variable through every IsX function CFML's got 'til it either finds a match or comes up empty, but if I could find a more elegant solution (ideally without diving down to the Java layer, though I suppose I've gotta learn someday) that'd be ideal.

      Any ideas?
        • 1. Re: Determining variable type at runtime
          Grizzly9279 Level 1
          Since ColdFusion is so loosely typed, it is almost impossible to deterministically identify a datatype for a given variable.

          Like you forshadowed in your original post, you can tunnel down into the Java layer and use the ".GetClass().GetName()" method, but more often than not you'll find that many variables are stored as string objects under the hood.

          You can force a datatype on a variable using the JavaCast() function, but short of that, there's no easy way to determine the datatype of a variable that was initialized without JavaCast().

          I think you'll find the following blog article fairly relevant:
          http://www.bennadel.com/blog/380-ColdFusion-Data-Types-From-Different-Sources-And-How-Cold Fusion-Sees-Them-.htm

          In any event, I think the best you can do is write a UDF that leverages the isArray, isQuery, isNumeric, isXML (etc etc) methods to determine a type. Of course, you'll have to be careful in how you order your tests.