我想将Java类发送给一个方法,并以arg的形式接收它,该arg具有与我发送的类相同的类型,每次调用此方法时,我都有一个新类发送给它。
示例: 这是我创建的类中的方法,并且有一种通用的T,但是我尝试过的这种方法不起作用
<T> void getBedInfo(final RecyclerView MainRecycler, Class<T> adapterName){
BedInfoGetter.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
if(e!=null){
return;
}
BedInfo.clear();
for(QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
Bed oneBedInfo = documentSnapshot.toObject(Bed.class);
activeValue = documentSnapshot.getId();
oneBedInfo.getId(activeValue);
BedInfo.add(oneBedInfo);
}
Adpter=new Adpter(BedInfo, context, activity);
MainRecycler.setAdapter(AOP);
MainRecycler.setItemAnimator(new DefaultItemAnimator());
}
});
}
这是方法的调用
databaseHandler.getBedInfo(MainRecycler, AdapterOnePatient.class);
希望我能解释我遇到的问题 非常感谢!
答案 0 :(得分:0)
您需要做的是创建一个BaseAdapter:
class BaseAdapter {
BaseAdapter(BedInfo info, Context context, Activity activity) {
//...
}
}
然后,您需要修改方法以仅接受扩展BaseAdapter的泛型:
<T extends BaseAdapter> void getBedInfo(final Recycler recycler, Class<T> adapterName) {
BedInfoGetter.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
if (e != null) {
return;
}
BedInfo.clear();
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
Bed oneBedInfo = documentSnapshot.toObject(Bed.class);
activeValue = documentSnapshot.getId();
oneBedInfo.getId(activeValue);
BedInfo.add(oneBedInfo);
}
T adapter = new BaseAdapter(info, context, activity);
MainRecycler.setAdapter(adapter);
MainRecycler.setItemAnimator(new DefaultItemAnimator());
}
});
}
第三步是像这样使用它:
getBedInfo(recycler, AdapterOnePatient.class);