繁体   English   中英

是否可以在不传递方法参数的情况下访问其他 class 方法

[英]Is it possible to access other class method without passing method parameter

我有一个场景,我想访问另一个 class 方法,该方法正在返回一些东西。

另一个 class 中的方法是期望参数

例子:

public class Class1()
{
    public Response postResponse(String getURL,DataTable dataTable)
    {
        /*..
        my post request code here
        ..*/
        return postData;
    }
}

public class Class2()
{
    public void readPostResponse()
    {
        /*..
         here i want to access Class1.postResponse method and I don't want to pass the 
         parameter.. 
        ..*/
    }
}

请让我知道如何实现这一目标。

你有三个选择:

  • 传递参数。 这是首选方式。 因为方法的参数包含一些可以在方法中使用的信息
  • 如果可能的话,模拟或存根你的参数。 看起来你正在使用 Selenium,但是 Selenium 启动了一个真正的浏览器
  • 传递 null 参数。这不是真正的首选方式,因为您的方法在没有必要数据的情况下可能无法正常工作

在@StepUp 发布他的答案之前,我开始写这篇文章。 我将根据我对“我不想传递参数”的理解来介绍我认为应该完成的方式

听起来您想创建一个默认案例。 这个例子是任意的,因为你的代码不是很具体。 一般来说,在谈论函数时,function 的默认情况是具有相同名称的方法,没有参数列表。 例如,

public class Class1 
{
    /**
     * Default case
     */
    public Response postResponse() 
    {
        // Some code here
    }

    /**
     * Specific case (the ellipsis means some parameter list) 
     */
    public Response postResponse(...)
    {
        // Some code here
    }
}

在您的情况下,您可能希望创建一个可以在特定场景中独立调用的默认步骤定义,或者您可能希望在数据表中指定或不指定参数的情况下从相同的场景中调用它。 你仍然可以采取同样的方法。 我想提一下,有一个默认情况,并不意味着你绝对需要传递 null 参数。 99% 的情况下,这是一个坏主意。 您需要做的就是传递一些默认值。

public class Class1 
{
    /**
     * Default case
     */
    public Response postResponse() 
    {
        String url = "..."; // maybe a base URL here?
        Object col1 = ...;
        Object col2 = ...;
        handlePostResponse(url, col1, col2);
        // Do other stuff?
        return response;
    }

    /**
     * Specific case 
     */
    public Response postResponse(String url, DataTable dataTable)
    {
        // Iterate through data table and call handlePostResponse for each row
        return response;
    }


    // This method wraps how to handle post response. The ellipsis might be the elements of the data table
    private void handlePostResponse(String url, Object col1, Object col2) 
    {
        // Do something
    }
}

现在您有了这个,您可以在 Class 2 中调用您的方法,该方法需要在 Class 1 中调用默认情况。

public class Class2 
{
    public void readPostResponse()
    {
        Class1 clazz1 = new Class1();
        Response resp = clazz1.postResponse(); // calling no parameters (default) case (you may not need to get the response object (ignore it altogether)
        // Do more stuff?
    }
}

Remember that every time you pass null to a function or return null from a function, you may have to do some sort of input or output validation to ensure the object about to be used to invoke other methods is not null. 不这样做会导致 Null 指针异常。

最后一点:我使用Object只是为了说明。 在您的情况下,它将是每列代表的任何类型的 object。 最有可能的是String ,但也可能是数字包装器(即Integer )或您可能为您的场景创建的一些自定义数据类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM