簡體   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