commons-beanutilsを使用してネストされたBeanにアクセスするときにNPEを防ぐ方法はありますか?これが私のコードです:
new BeanUtilsBean().getProperty(human, "parent.name");
この場合getProperty()
、空の文字列( "")を返すかhuman.getParent() == null
、NPEをスローする以外の方法で処理します。
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(...)
は、をスローすることによって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);
}
}