8

As part of the implementation of an API, I would like to be able to find the SObjectType from the SObjectField:

public class MyClass {
    // Fields are from various SObjects
    public void myMethod(SObjectField[] fs) {
        for (SObjectField f : fs) {
            DescribeFieldResult dfr = f.getDescribe();
            SObjectType t = ...;
            ...;
        }
    }
}

but even in the describe results it does not appear to be present. Am I missing something?

6

I don't believe this is possible currently. There's no methods on Schema.SObjectField of Schema.DescribeFieldResult that link back to the SObjectType that field belongs to.

| improve this answer | |
1

I know this is a little old, but I was searching how to solve this problem and I couldn't find anything useful. This is how I solved it:

Type myObjectType = MyObject__c.myField__c.class;
String myObjectName = myObjectType.toString(); // You can use getName() as well

That code will give you the Type of MyObject__c class. Then you can use all the methods for Type class in Apex like toString() or getName() to get the String name of MyObject__c.

Please check Salesforce Type Class for more info.

| improve this answer | |
0

Found this in the documentation for the DescribeFieldResult class, maybe it will help

getReferenceTo()

Returns a list of Schema.sObjectType objects for the parent objects of this field. If the isNamePointing method returns true, there is more than one entry in the list, otherwise there is only one

Signature public List <Schema.sObjectType> getReferenceTo()

Return Value Type: List<Schema.sObjectType>

LINK

| improve this answer | |
  • I'm afraid that relates to the type of the object referenced by the field not the type of the object containing the field. But thanks for taking a look. – Keith C Mar 12 '14 at 10:45
  • Yup, you are correct. Sorry about that.. – Eric Mar 12 '14 at 17:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.