Tôi đang xử lý thư Google Protobuf.Gọi phương thức tĩnh qua Method.invoke() đã cho tôi NPE
Vì nhu cầu của tôi là đặt trường mẫu của đối tượng (một số trong số đó là thông điệp Protobuff), tôi đã viết một hàm truy xuất thông qua trình tạo hình phản chiếu và thông qua protobuf-java-format tạo lại thư.
Dưới đây là đoạn code
for (String aFieldName : objectContentMap.keySet()) {
Object aFieldNameValue = objectContentMap.get(aFieldName);
if (aFieldNameValue != null) {
Field theClassField = this.instance.getField(aFieldName);
ReflectionUtils.makeAccessible(theClassField);
Class<?> classType = theClassField.getType();
if (!classType.isPrimitive() &&
GeneratedMessage.class.isAssignableFrom(classType.getSuperclass())) {
Method method = classType.getMethod("newBuilder");
// Since the method is static, the instance object that undergoes the call is not important, but with "null" I have a NPE...
Object builder = method.invoke(new Object());
if (builder instanceof Builder) {
Builder newBuilder = (Builder)builder;
InputStream asd = new ByteArrayInputStream(((String)aFieldNameValue).getBytes());
protoMapper.merge(asd, newBuilder);
aFieldNameValue = newBuilder.build();
}
}
theClassField.set(recreatedObject, aFieldNameValue);
}
}
đoạn này hoạt động như dự định, nhưng nghi ngờ của tôi là trong dòng Object builder = method.invoke(new Object());
kể từ khi tôi gọi các phương thức tĩnh tôi đã luôn đặt null
như tham số thực tế.
Trong trường hợp này, tôi đã có một NullPointerException.
Có ai đó biết tại sao có nhu cầu của một cá thể trong tham số thực tế invoke()?
Cảm ơn Dario.
Nếu gọi ném NPE, thì phương thức không tĩnh. Bạn có thể muốn kiểm tra xem Modifier.isStatic (method.getModifiers()) – Javier
@Javier: Tôi đã kiểm tra công cụ sửa đổi phương thức. Việc kiểm soát đã cho tôi thật không may. – Dario
nghi ngờ chính của tôi là ở phần protobuf. Tôi không có quá nhiều kinh nghiệm trong những lớp học rộng rãi này ... – Dario