Bean のネストされた/インデックス付きプロパティにアクセスするときに NPE を防ぐ方法
-
02-10-2019 - |
質問
commons-beanutils を使用してネストされた Bean にアクセスするときに NPE を防ぐ方法はありますか?これが私のコードです:
new BeanUtilsBean().getProperty(human, "parent.name");
この場合、私が欲しいのは getProperty()
空の文字列 ("") を返すか、 human.getParent() == null
または、NPE をスローする以外の方法で処理します。
解決
彼らは考えていました 追加する 言語機能は JDK7 に準拠していますが、 結局追加されなかった
現時点では手動で確認する必要があります。それをハッキングして次のような関数を作成することができます
public static void propertyHack(Object bean, String property, String nullreplace){
try{
return new BeanUtilsBean().getProperty(bean, property);
}
catch(NullPointerException npe){
return nullreplace;
}
}
ちょっとひどいですが、うまくいきます。
他のヒント
PropertyUtils
ネストされた特性のための特定の方法があります getNestedProperty(...)
それはaを投げることによってnpeを処理します NestedNullException
, 、おそらく(?)目にとっては良いです。
これが次のとおりです Javadoc.
他の誰かが答えを検索している場合
Guia g = new Guia();
GuiaParticipante gp = new GuiaParticipante(1);
g.setTbGuiaParticipanteCollection(Collections.singletonList(gp));//comment this line to test
String name = "tbGuiaParticipanteCollection[0].codParticipante";//the expression itself
Resolver resolver = new DefaultResolver();//used to "clean" the expression
if (resolver.isIndexed(name)) {
String property = resolver.getProperty(name);//remove the [0].codParticipante
if (PropertyUtils.getProperty(g, property) != null) { //get the collection object, so you can test if is null
String cod = BeanUtils.getNestedProperty(g, name); //get the value if the collection isn't null
System.out.println(cod);
}
}
所属していません StackOverflow