Menu Bar

Friday 26 February 2021

Call a method of one class in another class : APEX : Salesforce

 You can use two approaches:

1.Use Static methods


You cannot use controller2 instance methods here

public class controller2 
{
    public static string method2(string parameter1, string parameter2) {
        // put your static code in here            
        return parameter1+parameter2;
    }
    ...
}

In a separate class file call method2()

// this is your page controller
public class controller1
{
    ...
    public void method1() {
        string returnValue = controller2.method2('Hi ','there');
    }
}

2.Create an instance of the other class

public class controller2 
{
    private int count;
    public controller2(integer c) 
    {
        count = c;
    }

    public string method2(string parameter1, string parameter2) {
        // put your static code in here            
        return parameter1+parameter2+count;
    }
    ...
}

public class controller1
{
    ...
    public void method1() 
    {
        controller2 con2 = new controller2(0);
        string returnValue = con2.method2('Hi ','there');
    }
}

If your methods are in a package with a namespace

string returnValue = mynamespace.controller2.method2();
--------------------------------------------------------------

public class ClassA {

    public list<Account> method1(){
        
        List<Account> lstacc = [SELECT Id,Name from Account];
    	return lstacc;
    }

}
////////////////////////////////////////////////////////////////
public class ClassB {
	
    ClassA ca = new ClassA();
    List<Account> acc = ca.method1();
    
    public static list<Contact> method2(List<Account> accountList){
        
        List<Contact> lstcon = [SELECT Id,LastName from Contact WHERE accountId IN: accountList];
        SYstem.debug('List of contact--->'+ lstcon);
        return lstcon;
    }
}

2 comments:

Steven Cohen said...

Login Your Meta Fx Global Account To Read The Latest News About The Platform.

Steven Cohen said...

If You Own A Forex Account, Meta Fx Global Is A Tool That You Need To Add To Your Trading Portfolio.