4

commons-beanutilsを使用してネストされたBeanにアクセスするときにNPEを防ぐ方法はありますか?これが私のコードです:

new BeanUtilsBean().getProperty(human, "parent.name");

この場合getProperty()、空の文字列( "")を返すかhuman.getParent() == null、NPEをスローする以外の方法で処理します。

4

3 に答える 3

2

彼らはJDK7に言語機能を追加することを考えていましたが、最終的には追加されませんでした

今のところ、手動​​で確認する必要があります。あなたはそれをハックして、次のような関数を作成することができます

public static void propertyHack(Object bean, String property, String nullreplace){
  try{
    return new BeanUtilsBean().getProperty(bean, property);
  }
  catch(NullPointerException npe){
    return nullreplace;
  }
}

ちょっとひどいですが、それはうまくいくでしょう。

于 2010-05-02T11:28:08.820 に答える
2

PropertyUtilsgetNestedProperty(...)は、をスローすることによってNPEを処理するネストされたプロパティの特定のメソッドを持っていますNestedNullException。これは、おそらく(?)目には優れています。

これがJavadocです。

于 2013-07-12T06:53:37.300 に答える
1

他の誰かが答えを探しているなら

    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);
        }
    } 
于 2014-04-23T14:11:54.010 に答える