变量在不同的类中不可用

时间:2012-05-31 17:56:24

标签: cloud salesforce apex-code

我有两个全球课程。在CreateAndModify类中,我有一个执行函数,它有一个for循环,它调用我的另一个类的processRecord方法,即CreateAndModifyProcessor。问题是在我的第一个类中声明了一个列表集合,我无法在第二个类中访问它。有没有办法做到这一点,这样做甚至是一个很好的想法吗?...

global class CreateAndModify implements
Database.Batchable<sObject>, Database.Stateful{

global void execute(
Database.BatchableContext BC,

List<sObject> listObj){

list <Account__c> inAcc = new list<Account__c>();

for (sObject lo : listObj){
      processor.processRecord(lo);
}

insert inAcc; // The list object which i 
              // am modifying in the processRecord function has to be added to       
              // the database. So, is it a good idea to add/populate the            
              // in other function of other class
}


global class CreateAndModifyProcessor {
global void processRecord(sObject listObj){
Unprocessed_Agreement__c temp = (Unprocessed_Agreement__c)listObj;

Account__c tempAcc = new Account__c();

inAcc.add(tempAcc); // This line throws an error
}
}

3 个答案:

答案 0 :(得分:3)

您的列表inAcc是在execute方法中定义的,因此它的范围仅限于该方法,并且不在其外部或方法所属的类中可用。如果您必须保留已经布局的结构,那么为什么不将帐户列表作为参数传递给处理方法,如下所示?

global class CreateAndModify implements
    Database.Batchable<sObject>, Database.Stateful {

    global void execute(Database.BatchableContext BC, List<sObject> listObj) {

        list <Account__c> inAcc = new list<Account__c>();

        for (sObject lo : listObj) {
            processor.processRecord(lo, inAcc);
        }

        insert inAcc;
    }
}

global class CreateAndModifyProcessor {

    global void processRecord(sObject listObj, list<Account> listAcc) {
        Unprocessed_Agreement__c temp = (Unprocessed_Agreement__c)listObj;
        Account__c tempAcc = new Account__c();
        listAcc.add(tempAcc);
    }
}

答案 1 :(得分:0)

list <Account__c> inAcc = new list<Account__c>();不是全球名单!

你应该把它移到execute方法之外,做这样的事情

global class CreateAndModify implements Database.Batchable<sObject>, Database.Stateful{ 

   global  list <Account__c> inAcc = new list<Account__c>();

  global void execute(Database.BatchableContext BC, List<sObject> listObj){

      for (sObject lo : listObj){
      processor.processRecord(lo);
       }

   insert inAcc; 
 }
}

答案 2 :(得分:0)

您是否考虑过对代码进行重组,以便从processRecord返回帐户或帐户列表并以这种方式将其添加到inAcc?它可能看起来像这样:

list <Account__c> inAcc = new list<Account__c>();

for (sObject lo : listObj){
    inAcc.addAll(processor.processRecord(lo));
}

insert inAcc;

global class CreateAndModifyProcessor {
    global list<Account> processRecord(sObject listObj){
        list<Account> accs = new list<Account>();
        Unprocessed_Agreement__c temp = (Unprocessed_Agreement__c)listObj;
        ... // some code that adds records to accs
        return accs;
    }
}