本文介绍了在Java中为通用protobuffer类调用parseFrom()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用api以获取输入流,然后调用静态方法parseFrom(inputstream)将其转换为protobuff类.

I'm calling an api to get the an input stream and then call static method parseFrom(inputstream) to convert it to the protobuffclass.

如果我通过特定的类来做的话,它将起作用:

If I do it with a specific class it works:

public CustomerDTOOuterClass.CustomerDTO GetCustomer()
{
    CustomerDTOOuterClass.CustomerDTO customer = null;
    try
    {
        URL url = new URL("https://localhost:44302/Api/customer/1?");

        HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/x-protobuf");
        conn.connect();

        InputStream is = conn.getInputStream();

        CustomerDTOOuterClass.CustomerDTO customer =
                CustomerDTOOuterClass.CustomerDTO.parseFrom(is);

        conn.disconnect();
    }
    catch(Exception ex)
    {
        System.out.println("[ "+ex.getMessage()+" ]");
    }

    return customer;
}

但是如果我将其更改为通用类型,则会失败,因为T没有方法parseFrom,我可以在T中实现任何接口,所以我可以调用parseFrom方法吗?

but if I change it to generic type it fails because T doesn't have the method parseFrom, is there any interface I could implement in T so I can call the parseFrom method?

public T GetObject()
{
    T object = null;
    try
    {
        URL url = new URL("https://localhost:44302/Api/customer/1?");

        HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/x-protobuf");
        conn.connect();

        InputStream is = conn.getInputStream();

        T object = T.parseFrom(is);

        conn.disconnect();
    }
    catch(Exception ex)
    {
        System.out.println("[ "+ex.getMessage()+" ]");
    }

    return object;
}

这是我得到的错误: 错误:(68,27)错误:找不到符号方法parseFrom(InputStream)

this is the error I get: Error:(68, 27) error: cannot find symbol method parseFrom(InputStream)

推荐答案

每个生成的protobuf类型都包含一个名为PARSER的静态成员,该成员是 com.google.protobuf.Parser<T> 接口.您的getObject方法仅需要将Parser<T>作为参数.因此,您可以这样称呼它:

Every generated protobuf type contains a static member called PARSER which is an implementation of the com.google.protobuf.Parser<T> interface. Your getObject method simply needs to take a Parser<T> as a parameter. So then you'd call it like:

Foo foo = getObject(Foo.PARSER);

这篇关于在Java中为通用protobuffer类调用parseFrom()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:56