如何使用未知类作为参数重构方法?

时间:2017-08-14 18:39:01

标签: java object methods delegates

我想让这个方法可以重用,但我不确定如何提供一个适用于以下环境的参数:

  • service.getPosts() // The method called, i.e. getPosts() should vary depending on the class parameter
  • for (Post object : postResponse.getResults()) { // I want the Post class to come from the parameter
  • List<Post> objects = postResponse.getResults(); // I want the class passed into this list to also come from that same parameter

方法调用:

retrieveData(mCardAdapter, Post.class);

方式:

private void retrieveData(final CardAdapter mCardAdapter, final Class classParam) {
        RetrofitService service = ServiceFactory.createRetrofitService(RetrofitService.class, RetrofitService.SERVICE_ENDPOINT);
        service.getPosts()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<PostResponse>() {
                    @Override
                    public final void onCompleted() {
                        setRefreshingFalse();
                        Log.e("RetrofitService", "Retrofit Request Completed!");
                    }

                    @Override
                    public final void onError(Throwable e) {
                        setRefreshingFalse();
                        Log.e("RetrofitService", e.getMessage());
                    }

                    @Override
                    public final void onNext(PostResponse postResponse) {
                        if (postResponse != null) {
                            Log.e("RetrofitService", "Returned objects: " + postResponse.getResults());

                            for (Post object : postResponse.getResults()) {
                                Log.e("RetrofitService", object.getObjectId() + ": " + object.getText());
                            }

                            /*for (Post post : postResponse.getResults()) {
                                mCardAdapter.addData(post);
                            }*/

                            setRefreshingFalse();

                            mCardAdapter.clear();
                            List<Post> objects = postResponse.getResults();
                            mCardAdapter.addData(objects);

                        } else {
                            Log.e("RetrofitService", "Object returned is null.");
                        }

                    }

                });
    }

当我通过Class classParam时,我只是将Unkown class: 'classParam'作为错误。

服务

public interface RetrofitService {

    String SERVICE_ENDPOINT = "https://parseapi.back4app.com";

@Headers({
            "X-Parse-Application-Id: asdf",
            "X-Parse-REST-API-Key: asdf"
    })
    @GET("/classes/Post")
    Observable<PostResponse> getPosts();

}

发布对象:

public class Post implements Serializable {

    private static final String CLASS_NAME = "Post";

    private String objectId;
    private String text;

    public Post() {
    }

    public String getClassName() {
        return CLASS_NAME;
    }

    public String getObjectId() {
        return objectId;
    }

    public void setObjectId(String objectId) {
        this.objectId = objectId;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}

更新(根据罗马的建议):

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

您没有显示PostResponse代码,但我认为它是这样的:

public class PostResponse {
    private List<Post> results;

    public List<Post> getResults() {
        return results;
    }

    ....
}

然后你可以做这样的事情。

首先,参数化Response(代替PostResponse使用):

public class Response<T> {
    private List<T> results;

    public List<T> getResults() {
        return results;
    }

    ....
}

其次,使用类型参数更改主方法签名:

private <T> void retrieveData(final CardAdapter mCardAdapter, final Class<T> classParam, DataSaver<T> saver) {
...
}

retrieveData()方法中,您使用T代替PostResponse<T>代替PostResponse

但你还必须处理

mCardAdapter.addData(objects);

这里,简单的类型参数化很可能不起作用。您必须使用最后一个参数(saver)将结果放入容器中:

saver.save(results);

并在您实际执行的saver实施中

public void save(List<Post> posts) {
    mCardAdapter.addData(posts);
}

DataSaver也是通用的:

public interface DataSaver<T> {
    void save(List<T> objects);
}