Using mauForceDev's answer I've written out a far more fleshed out version.
Please note, my actual implementation is not the version I'm posting here (it's far more complex), so this version is untested. But it should work fine.....
First, define a results class and a method to automate going from an unknown object ID into a set of results that gives us the related field we are looking for and the original ID's object. Everything we need to start processing data! :)
public class fieldHunterResults{
public String fieldName = '';
public String objectType = '';
public Boolean isFound = false;
}
public fieldHunterResults fieldHunt(Id related_object_id,String field_type){
fieldHunterResults results = new fieldHunterResults();
//Just make sure null isn't sent
if(related_object_id!=null){
Schema.SObjectType token = related_object_id.getSObjectType();
Schema.DescribeSObjectResult dr = token.getDescribe();
//Foreach field
for(Schema.Sobjectfield field : dr.fields.getMap().values()){
//Check to see if there is any related fields
List<Schema.SObjectType> related_fields = field.getDescribe().getReferenceTo();
if(related_fields.size()>0){
SObjectType related_field = related_fields[0];
//Check to see if the related fields matchs the one we are looking for
if(related_field.getDescribe().getName()==field_type){
//Eureka! Found the related field! Fill up the results with what we found and return
results.fieldName = field.getDescribe().getName();//These lines can be optimised
results.objectType = token.getDescribe().getName();//These lines can be optimised
results.isFound = true;
return results;
}
}
}
}
//Nothing was found :(
return results;
}
An example of how to use:
fieldHunterResults check_fields = fieldHunt(some_object_id,'Account');
//Perform a dynamic SOQL based on the info we grabbed. We have grabbed the relevant information for this, field and object name
if(check_fields.isFound){
List<sObject> L = Database.query('SELECT '+check_fields.fieldName+' FROM ' + check_fields.objectType +' WHERE Id =:some_object_id');
Account account = new Account(Id=L[0].get('Id'));//Don't do this in production, this is shorthand and prone to errors. But fine for an example
account.Some_Value__c = 'Something';
update account;
}