【问题标题】:"Standard simple" interfaces in Java?Java中的“标准简单”接口?
【发布时间】:2016-12-08 14:52:45
【问题描述】:

所以我在 Java 中编写了一个典型的类,用于将 json 发送到休息服务器。 (为了清楚起见,我将在下面包含整个类。)这是一个文件 "Fetcher.java"

现在对于回调,您需要一个接口。接口很简单,只有一个带字符串的函数。

public interface FetcherInterface {
    public void fetcherDone(String result);
}

烦人的是,你需要一个完整的文件,"FetcherInterface.java"

所以这个接口只不过是“一个带有字符串的回调”。通常你所需要的只是“一个没有参数的回调”。

事实上.......有一些我可以使用的标准接口,或者类似的东西吗?

对于这么简单的“标准”界面,不得不放入一个完整的界面似乎有点烦人。

这是怎么回事? javaly的解决方案是什么?

您似乎不能将它放在同一个文件中

也许我误解了那里的东西。如果你能把它放在同一个文件中,至少会很方便。

(Lambdas 尚未实际可用。无论如何,有时您需要一个接口。)


为了清楚起见,这里是你如何称呼这个类

    JSONObject j = new JSONObject();
    try {
        j.put("height", 2.1);
        j.put("width", 2.5);
        j.put("command", "blah");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    new Fetcher("mobile/login", j, new FetcherInterface() {
                @Override
                public void fetcherDone(String result) {
                    Log.d("DEV","all done");
                    doSomething(result);
                }
        }
    ).execute();

确实

public class HappyClass extends Activity implements FetcherInterface {
...

private void someCall() {
    JSONObject j = new JSONObject();
    try {
        j.put("height", 2.1);
        j.put("width", 2.5);
        j.put("command", "blah");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    new Fetcher("mobile/data", j, this).execute();
    devBlank();
}

@Override
public void fetcherDone(String result) {
    Log.d("DEV","all done" +result);
    doSomething(result);
}

这是整个类... Fetcher.java 文件

public class Fetcher extends AsyncTask<Void, Void, String> {

    private String urlTail;
    private JSONObject jsonToSend;
    private FetcherInterface callback;

    // initializer...
    Fetcher(String ut, JSONObject toSend, FetcherInterface cb) {
        urlTail = ut;
        jsonToSend = toSend;
        callback = cb;
    }

    @Override
    protected String doInBackground(Void... params) {

        HttpURLConnection urlConnection = null; // declare outside try, to close in finally
        BufferedReader reader = null;           // declare outside try, to close in finally
        String rawJsonResultString = null;
        String json = jsonToSend.toString();

        Log.d("DEV","the json string in Fetcher is " +json);

        try {
            URL url = new URL("https://falcon.totalfsm.com/" + urlTail);

            Log.d("DEV","the full URL in Fetcher is " +url);

            // open a json-in-the-body type of connection.......
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setConnectTimeout(5000);
            // urlConnection.setDoOutput(false); // can be important?

            urlConnection.connect();

            OutputStream os = urlConnection.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            os.close();

            // annoyingly, you have to choose normal versus error stream...
            InputStream inputStream;
            int status = urlConnection.getResponseCode();
            if (status != HttpURLConnection.HTTP_OK)
                inputStream = urlConnection.getErrorStream();
            else
                inputStream = urlConnection.getInputStream();
            if (inputStream == null) { // nothing to do.
                return null;
            }

            StringBuffer buffer = new StringBuffer();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) { // adding newlines makes debugging easier
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) { // stream was empty
                return null;
            }

            rawJsonResultString = buffer.toString();
            return rawJsonResultString;

        } catch (IOException e) {
            Log.e("PlaceholderFragment", "Error ", e);
            return null;
        } finally{
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PlaceholderFragment", "Error closing stream", e);
                }
            }
        }
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.d("DEV", "Fetcher done");
        if (s==null) {
            Log.d("DEV","applying anti-null measures in Fetcher!");
            s = "message from app communications layer: 'null' returned from servers for that call at " +urlTail;
        }
        callback.fetcherDone(s);
    }
}

【问题讨论】:

  • 根据the docs,Android 支持 lambdas。如果您的目标是 API 级别 23 或更低,则需要做一些额外的工作。
  • 嗨 Ted,谢谢,正如我提到的,我很欣赏 lambdas 是一种未来的可能性。你知道我关于接口的问题有答案吗?是否有“标准接口”或类似的东西?
  • 如果你想要一个公共接口,它在它自己的文件中。这就是 Java 的工作原理。
  • 这是一个很棒的提示@Rotwang,谢谢。在许多情况下,这似乎是个好习惯。然后你必须implements Fetcher.ThatName 可能有点烦人,但是是的,太棒了。
  • 对我来说,这里有明确的答案 == “如果你想要一个公共接口,它就在它自己的文件中。这就是 Java 的工作原理。” + "对于本地接口,在类内部使用受保护的接口,实现 ClassName.InterfaceName"

标签: android interface


【解决方案1】:

我很难回答自己的问题,但由于没有其他答案,此信息可能会有所帮助。

DaveNewton 和 Rowtang 在这里提供了确切的答案:

(第 1 点)如果您想要一个真正的 public 界面,它可以放在自己的文件中。这就是 Java 的工作原理。别无选择。

(第2点)通常,使用protected interface并在类内部声明接口。然后可以在整个应用程序中使用它。

所以...

public class Fetcher extends AsyncTask<Void, Void, String> {

    protected interface FetcherInterface {
        public void fetcherDone(String result);
    }

    private String urlTail;
    private JSONObject jsonToSend;
    private FetcherInterface callback;

    Fetcher(String ut, JSONObject toSend, FetcherInterface cb) {
        urlTail = ut;
        jsonToSend = toSend;
        callback = cb;
    }

    @Override
    protected String doInBackground(Void... params) {
    ....

(c# 程序员可能会称它为“IFetcher”。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 2013-09-20
    • 1970-01-01
    • 2012-04-09
    相关资源
    最近更新 更多