Android:方法回调无法正常工作

时间:2016-10-26 07:38:28

标签: java android reflection

我正在尝试使用relection实现方法回调,但它没有调用所需的方法。这是我的主要活动

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RetrofitCalls retrofitCalls = new RetrofitCalls();
        retrofitCalls.requestAccesstoken();
        retrofitCalls.requestDataFromServer(MainActivity.this,"onCountryListReceived");
    }

    public void onCountryListReceived(JsonObject jsonObject)
    {
        String temp = "hello";
    }
}

这是requestDataServer方法

 public void requestDataFromServer(final Activity activity, final String callBackMethod){

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new HeaderInterceptor())
            .build();

    retrofit = new Retrofit.Builder()
            .baseUrl(Constants.ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    Api api = retrofit.create(Api.class);
    Call<JsonObject> call = api.getDataFromServer(Constants.COUNTRY_LIST);
    call.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {

            if(response.errorBody() != null){
                try {
                    String j1 = response.errorBody().string();
                    String temp = "hello";
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }else if(response.body() != null) {
                JsonObject jsonObject = response.body();
                JsonArray jsonArray = jsonObject.getAsJsonArray("Data");
                String temp = "hello";

                try {
                    String x = activity.getClass().toString();
                    Method method = activity.getClass().getDeclaredMethod(callBackMethod.trim(),Object.class);
                    method.invoke(activity,jsonObject);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            String temp = "hello";
        }
    });
}

为什么不调用onCountryListReceived?它正在给NoSuchMethodException。问题是什么?

1 个答案:

答案 0 :(得分:0)

我在getDeclaredMethod中传递了JsonObject.class而不是Object.class,因为它是要调用的方法的参数。
getDeclaredMethod接受两个参数
1.callback方法名称2.该方法的参数。