如何在apex中将类的方法调用到另一个类中

Anu*_*Raj 3 salesforce force.com apex-code

我想将一个类的方法用于另一个类.

     eg: public class controller 1{
          public void method 1(){}
      }


     public class controller 2{
         public void method 2() { }     
       } 
Run Code Online (Sandbox Code Playgroud)

我想在类controller2中使用method1.请帮我找到解决方案

Ger*_*ton 7

您可以使用两种方法:

1.使用静态方法

您不能在此处使用controller2实例方法

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

在单独的类文件中调用method2()

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

2.创建另一个类的实例

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您的方法位于具有命名空间的包中

string returnValue = mynamespace.controller2.method2();
Run Code Online (Sandbox Code Playgroud)