List
zawiera typ obiektu, ale muszę sprawdzić, czy dany obiekt jest typu A
lub B
:Sprawdź, który typ obiektu List <?> zawiera
A a = new A();
B b = new B();
List<A> aL = new ArrayList<A>();
List<B> bL = new ArrayList<B>();
Jak mogę sprawdzić, czy List
zawiera A
przedmiotów lub B
obiekty?
Oto kod:
SegmentDetailInfo segmentDetailInfo = new SegmentDetailInfo();
segmentDetailInfo.setSeg_Id("1");
SegReqInfoBean segReqInfoBean = new SegReqInfoBean();
segReqInfoBean.setPageName("homepage");
List<SegmentDetailInfo> rhsList1 = new ArrayList<SegmentDetailInfo>();
rhsList1.add(segmentDetailInfo);
List<SegReqInfoBean> rhsList2 = new ArrayList<SegReqInfoBean>();
rhsList2.add(segReqInfoBean);
doProspecListCompareCheck(rhsList1);
doProspecListCompareCheck(rhsList2);
}
private static void doProspecListCompareCheck(Object rhsList) {
if (rhsList instanceof List<SegmentDetailInfo>) //wrong Check
//DoTHIS
else if(rhsList instanceof List<SegReqInfoBean>) //wrong Check
//Do THIS
}
================================== ======================
SegmentDetailInfo segmentDetailInfo = new SegmentDetailInfo();
segmentDetailInfo.setSeg_Id("1");
SegReqInfoBean segReqInfoBean1 = new SegReqInfoBean();
segReqInfoBean1.setPageName("Home");
List<SegmentDetailInfo> rhsList1 = new ArrayList<SegmentDetailInfo>();
rhsList1.add(segmentDetailInfo);
List<SegReqInfoBean> rhsList2 = new ArrayList<SegReqInfoBean>();
rhsList2.add(segReqInfoBean1);
String Homepage="homepage";
doProspecListCompareCheck(Homepage);
doProspecListCompareCheck(rhsList2);
doProspecListCompareCheck(rhsList2);
private static void doProspecListCompareCheck(Object rhsListObj) {
List<String> rhsStrList = new ArrayList<String>();
List<SegReqInfoBean> segReqInfoBeanList = new ArrayList<SegReqInfoBean>();
List<SegmentDetailInfo> segmentDetailInfoList = new ArrayList<SegmentDetailInfo>();
if (rhsListObj != null && rhsListObj instanceof List) {
if (((List<SegmentDetailInfo>) rhsListObj).get(0) instanceof SegmentDetailInfo){
System.out.println("SegmentDetailInfo loading");
segmentDetailInfoList = (List<SegmentDetailInfo>) rhsListObj;
}
else if(((List<SegReqInfoBean>) rhsListObj).get(0) instanceof SegReqInfoBean){
System.out.println("SegReqInfoBean loading");
segReqInfoBeanList = (List<SegReqInfoBean>) rhsListObj;
}
}else if (rhsListObj != null && rhsListObj instanceof String) {
rhsStrList.add(rhsListObj.toString());
}
}
Usunięcie typu uniemożliwia takie działanie. –
W tym * bardzo wąskim * scenariuszu, prawdopodobnie mógłbyś sprawdzić '((List) rhsList) .get (0) instanceof SegReqInfoBean'. Wymaga, abyś miał coś na liście, w przeciwnym razie nie da się tego powiedzieć. – Dennis