# Get namespace prefix for a field

In a question I asked last week about getting namespaces, the best solution was to get information about the class (or any class) in the namespaced package.

But this seems vulnerable if there are other classes with the same name. It also assumes that the utility class is packaged with the object whose namespace we want.

What I really want is to get the namespace that a field belongs to, because the get() and put() methods on an object are namespaced.

So I have to say

Account a = [SELECT some account];
a.put('namespace__Field__c', 35);


not

Account a = [SELECT some account];
a.put('Field__c', 35);


Can I query a fields namespace, to make the above operation more robust?

[The context of this question: We emulate roll-up summary functionality in a trigger, with a "group by" on a Type__c field. We then take the field on Account that matches the "type" and assign it the count in its corresponding group.]

Remember that the whole point of the namespacing is to allow multiple fields of the same name to exist. So fields Abc__c, pqr__Abc__c and xyz__Abc__c might all exist in an org. For non-namespaced code, the fully qualified name e.g. xyz__Abc__c or Abc__c has to be used to identify the correct field.
But things are a bit different for code in the namespaced managed package. In that case, assuming the namespace is xyz, then both Abc__c and xyz__Abc__c will reference the same field because the platform automatically defaults the namespace. Effectively the non-namespaced field Abc__c is hidden by the namespaced field xyz__Abc__c for the code in the managed package.