我正在編寫一個方法,如果異常是 的實例,該方法將返回 true *someClass*。但我無法導入其中一個類,因為它位于另一個模塊中。我無法將該模塊添加到項目中,所以我想,我無法使用instanceof。我考慮創建一個Mapof Strings- 異常的類名并檢查我的異常的類名是否在映射中,但我認為這會相當慢且難看。方法如下:public boolean checkExceptionClass(Throwable cause){ return (cause instanceof firstException || cause instanceof secondException || cause instanceof iDontHaveThatClassException // can't do that || cause instanceof fourthException);}也許我在我眼皮子底下看不到解決這個問題的好辦法。非常感謝任何想法和建議。
1 回答

智慧大石
TA貢獻1946條經驗 獲得超3個贊
您可以嘗試使用 .getClass() 和 getSimpleName(),例如:
Integer integer = Integer.valueOf(1);
if(integer.getClass().getSimpleName().equals("Integer") {
return true
}
所以基本上你可以使用你無法導入的類的名稱,值得一提的是,硬編碼不是最佳實踐
添加回答
舉報
0/150
提交
取消