Android,如何将变量作为指针传递给函数?

时间:2013-02-20 16:42:15

标签: java android

如何将变量作为指针传递给函数? 我有以下代码我想重构

    public static HttpResponse getJSONEntityFromURL(Context context, String url) throws ClientProtocolException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("Accept", "application/json");
        httpget.addHeader("Content-Type", "application/json; charset=UTF-8");
        HttpResponse response;

        response = httpclient.execute(httpget);
        return response;
    }

这样的事情

    public static HttpResponse getJSONEntityFromURL(Context context, String url) throws ClientProtocolException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
            setHeaders(httpget);
        HttpResponse response;

        response = httpclient.execute(httpget);
        return response;
    }

private static void setHeaders(HttpRequestBase httpget) {
    httpget.addHeader("Accept", "application/json");
    httpget.addHeader("Content-Type", "application/json; charset=UTF-8");
}

我假设我需要将httpget参数作为指针传递?

4 个答案:

答案 0 :(得分:3)

  

我假设我需要将httpget参数作为指针传递?

不,因为Java没有指针。

你在那里的代码似乎很好 - 你将HttpGet对象传递给setHeaders()并在其上调用方法。如果您对当前语法有特定问题,请解释。

答案 1 :(得分:1)

我会用那个

private static void setHeaders(final HttpRequestBase httpget) {
  httpget.addHeader("Accept", "application/json");
  httpget.addHeader("Content-Type", "application/json; charset=UTF-8");
}

确定它不是指针,但在这种情况下,引用httpget会在不返回HttpRequestBase的情况下进行更改。

答案 2 :(得分:1)

Java只允许传递引用,因为Java没有实现指针算法

所有基本类型都通过复制传递,所有对象类型都由ref传递。 (通过复制,但是内存地址的副本而不是复制整个对象。)

你认为的方式是正确的:

private static void setHeaders(HttpRequestBase AGet) {
    AGet.addHeader("Accept", "application/json");
    AGet.addHeader("Content-Type", "application/json; charset=UTF-8");
}

除非您需要在其他地方使用此方法,否则我建议使用第一个代码。

http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html< - documentation

答案 3 :(得分:1)

您可以使用HttpMessage界面,如下所示: -

http://developer.android.com/reference/org/apache/http/HttpMessage.html

这将允许您接受此接口的实现,即HttpGet的实例

即: -

private static void setHeaders(HttpMessage httpMessage) 
{
    httpMessage.addHeader("Accept", "application/json");
    httpMessage.addHeader("Content-Type", "application/json; charset=UTF-8");
}