12

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?

1

4 Answers 4

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.

3

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.

1
  • although this works (and is clever), OP has a variable of type Schema.SObjectField and I don't see how one gets from Account.Website to Account.Website.class to make your scheme work
    – cropredy
    Jan 13, 2021 at 0:13
2

Update Spring '23 v57.0

This is now possible using the getSObjectType() method.

e.g.

Schema.SObjectField myField = My_Object__c.My_Field__c;

Assert.areEqual(myField.getDescribe().getSObjectType(), My_Object__c.SObjectType);
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

2
  • 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, 2014 at 10:45
  • Yup, you are correct. Sorry about that..
    – Eric
    Mar 12, 2014 at 17:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .