fix NullPointerException when passing null as parameter of private accessor

This commit is contained in:
金戟 2021-10-17 15:46:35 +08:00
parent e1afb1cd54
commit 3bf19ee6d0
3 changed files with 13 additions and 5 deletions

View File

@ -46,7 +46,9 @@ public class DemoPrivateAccess {
* private member method with arguments
*/
private String privateFuncWithArgs(List<String> list, String str, int i) {
return list.stream().reduce((a, s) -> a + s).orElse("") + " + " + str + " + " + i;
return list.stream().reduce((a, s) -> a + s).orElse("")
+ " + " + (str == null ? "null" : str)
+ " + " + i;
}
}

View File

@ -52,7 +52,13 @@ class DemoPrivateAccessorTest {
void should_use_null_parameter() {
set(demoPrivateAccess, "pi", null);
assertNull(get(demoPrivateAccess, "pi"));
assertEquals("null + 1", invokeStatic(DemoPrivateAccess.class, "privateStaticFuncWithArgs", null, 1));
List<String> list = new ArrayList<String>() {{ add("a"); add("b"); add("c"); }};
String value = invoke(demoPrivateAccess, "privateFuncWithArgs", list, null, 0);
assertEquals("abc + null + 0", value);
value = invokeStatic(DemoPrivateAccess.class, "privateStaticFuncWithArgs", null, 1);
assertEquals("null + 1", value);
}
}

View File

@ -109,10 +109,10 @@ public class PrivateAccessor {
}
Class<?> commonClass = cls[0];
for (int i = 1; i < cls.length; i++) {
if (cls[i].isPrimitive()) {
return null;
} else if (cls[i] == null) {
if (cls[i] == null) {
continue;
} else if (cls[i].isPrimitive()) {
return null;
}
commonClass = getCommonClassOf(commonClass, cls[i]);
}