diff --git a/src/main/java/io/ljunggren/sanitizer/Sanitizer.java b/src/main/java/io/ljunggren/sanitizer/Sanitizer.java index 40c4f23..68e6871 100644 --- a/src/main/java/io/ljunggren/sanitizer/Sanitizer.java +++ b/src/main/java/io/ljunggren/sanitizer/Sanitizer.java @@ -61,12 +61,23 @@ private List findItems(Object object, List items) { List fields = findObjectFields(object); for (Field field : fields) { + boolean annotated = field.getAnnotations().length > 0; + boolean embeddable = checkEmbedded(field.getType()); + // Only fields that are either annotated or eligible for recursive descent + // are read. This also avoids forcing access to fields we have no use for, + // including JDK-internal fields (e.g. java.util.ArrayList#serialVersionUID) + // that the module system blocks reflective access to without --add-opens, + // which would otherwise throw when a JDK collection/object is passed in + // directly as the top-level sanitize() target. + if (!annotated && !embeddable) { + continue; + } try { Object value = FieldUtils.readField(field, object, true); - if (field.getAnnotations().length > 0) { + if (annotated) { items.add(new Item(object, field, value)); } - if (checkEmbedded(field.getType())) { + if (embeddable) { if (ReflectionUtils.isCollection(field.getType())) { @SuppressWarnings("unchecked") Collection embeddeds = (Collection) value; diff --git a/src/test/java/io/ljunggren/sanitizer/SanitizerExtraTest.java b/src/test/java/io/ljunggren/sanitizer/SanitizerExtraTest.java index dff5dfc..af0a2ac 100755 --- a/src/test/java/io/ljunggren/sanitizer/SanitizerExtraTest.java +++ b/src/test/java/io/ljunggren/sanitizer/SanitizerExtraTest.java @@ -104,4 +104,19 @@ new Sanitizer(pojo).sanitize(); assertEquals("Alex", pojo.getInners().get(0).getName()); } + + @Test + public void topLevelJdkCollectionDoesNotThrowTest() { + // regression test: sanitizing a raw JDK collection/object directly (no + // recursive(), no annotated fields of its own) used to force-read every + // field via reflection, including JDK-internal fields like + // ArrayList#serialVersionUID, which the module system blocks access to + // without --add-opens and throws InaccessibleObjectException for. A bare + // collection passed as the top-level object is never unwrapped into its + // elements (that only happens for collection-typed fields of a wrapper + // object), so this just needs to not throw and leave elements untouched. + List inners = new ArrayList<>(Arrays.asList(new Inner("Alex"))); + new Sanitizer(inners).recursive().sanitize(); + assertEquals("Alex", inners.get(0).getName()); + } }