I'm working on some of the Apex REST services for our CloudSpokes org and needed some code to fetch field level metadata using Apex Describe. I poked around and realized that there isn't really much out there. So I decided to write something up and hopefully people find it useful or instructional. Perhaps it should be part of apex-lang?
If you've ever worked with Apex Describe before you'll quickly realize that it's not the easiest thing to work with. You'll want to take a peek at the docs. Don't get me wrong, it's power, fast and very handy. But it is rather confusing and cumbersome to work with at first. So I wanted some code that returns the metadata for specific fields in an object so that I could look at field types and lengths and perform "stuff" accordingly.
So here's what I can up with. You pass the method the DescribeFieldResult for an object and a collection of fields that you want metadata for. The method returns a map where the field names are the keys and the values contain the metadata for the corresponding field. It looks pretty hard but that's the great thing about utility methods, they encapsulate and hide the complexity of the implementation.
So now in my code I can call this static method in my Utils class and access the field metadata easily by fetching it from the map by it's field name:
So if you run this, you'll see something like: