[英]How can I send unknown Class type to method and generate a parameter for that class
我想將一個 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);
希望我能解釋我遇到的問題 非常感謝!
您需要做的是創建一個 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.