كيفية منع NPE عند الوصول إلى خاصية متداخلة/مفهرسة من الفول
-
02-10-2019 - |
سؤال
هل هناك أي طريقة لمنع NPE عند الوصول إلى حبة متداخلة باستخدام Commons-Bunutils؟ ها هو رمزتي:
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
, ، والتي ربما تكون (؟) أفضل للعين.
ها هو جافادوك.
إذا كان شخص آخر يبحث في الإجابة
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