From 8252b04a45722648ce2225853de9882b3b0de034 Mon Sep 17 00:00:00 2001 From: Matthew Jason Benson Date: Mon, 20 Jan 2014 17:19:02 +0000 Subject: [PATCH] [LANG-613] ConstructorUtils.getAccessibleConstructor() Does Not Check the Accessibility of Enclosing Classes git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@1559779 13f79535-47bb-0310-9956-ffa450edef68 --- .../lang3/reflect/ConstructorUtils.java | 20 ++++++++++++++++++- .../lang3/reflect/ConstructorUtilsTest.java | 9 +++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java b/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java index 641c39b4c..5eca29439 100644 --- a/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java +++ b/src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java @@ -217,7 +217,7 @@ public class ConstructorUtils { public static Constructor getAccessibleConstructor(final Constructor ctor) { Validate.notNull(ctor, "constructor cannot be null"); return MemberUtils.isAccessible(ctor) - && Modifier.isPublic(ctor.getDeclaringClass().getModifiers()) ? ctor : null; + && isAccessible(ctor.getDeclaringClass()) ? ctor : null; } /** @@ -279,4 +279,22 @@ public class ConstructorUtils { return result; } + /** + * Learn whether the specified class is generally accessible, i.e. is + * declared in an entirely {@code public} manner. + * @param type to check + * @return {@code true} if {@code type} and any enclosing classes are + * {@code public}. + */ + private static boolean isAccessible(final Class type) { + Class cls = type; + while (cls != null) { + if (!Modifier.isPublic(cls.getModifiers())) { + return false; + } + cls = cls.getEnclosingClass(); + } + return true; + } + } diff --git a/src/test/java/org/apache/commons/lang3/reflect/ConstructorUtilsTest.java b/src/test/java/org/apache/commons/lang3/reflect/ConstructorUtilsTest.java index bfa6f51de..ac58ba961 100644 --- a/src/test/java/org/apache/commons/lang3/reflect/ConstructorUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/reflect/ConstructorUtilsTest.java @@ -18,7 +18,9 @@ package org.apache.commons.lang3.reflect; import org.junit.Test; import org.junit.Before; + import static org.junit.Assert.*; + import java.lang.reflect.Constructor; import java.util.Arrays; import java.util.HashMap; @@ -70,6 +72,12 @@ public class ConstructorUtilsTest { @SuppressWarnings("unused") public PrivateClass() { } + + @SuppressWarnings("unused") + public static class PublicInnerClass { + public PublicInnerClass() { + } + } } private final Map, Class[]> classCache; @@ -154,6 +162,7 @@ public class ConstructorUtilsTest { .getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY))); assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.class .getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY))); + assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.PublicInnerClass.class)); } @Test