Fix fallback behavior of UnsafeReflectionAllocator when AccessibleObject isn't so accessible

This commit is contained in:
Richard Hernandez 2020-05-26 20:12:06 -07:00
parent ceae88bd66
commit b39494dbe6
2 changed files with 27 additions and 1 deletions

View File

@ -79,7 +79,7 @@ final class UnsafeReflectionAccessor extends ReflectionAccessor {
private static Field getOverrideField() {
try {
return AccessibleObject.class.getDeclaredField("override");
} catch (NoSuchFieldException e) {
} catch (Exception e) {
return null;
}
}

View File

@ -15,10 +15,12 @@
*/
package com.google.gson.internal.reflect;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.lang.reflect.Field;
import java.security.Permission;
import org.junit.Test;
@ -41,6 +43,30 @@ public class UnsafeReflectionAccessorTest {
}
}
@Test
public void testMakeAccessibleWithRestrictiveSecurityManager() throws Exception {
final Permission accessDeclaredMembers = new RuntimePermission("accessDeclaredMembers");
final SecurityManager original = System.getSecurityManager();
SecurityManager restrictiveManager = new SecurityManager() {
@Override
public void checkPermission(Permission perm) {
if (accessDeclaredMembers.equals(perm)) {
throw new SecurityException("nope");
}
}
};
System.setSecurityManager(restrictiveManager);
try {
UnsafeReflectionAccessor accessor = new UnsafeReflectionAccessor();
Field field = ClassWithPrivateFinalFields.class.getDeclaredField("a");
assertFalse("override field should have been inaccessible", accessor.makeAccessibleWithUnsafe(field));
accessor.makeAccessible(field);
} finally {
System.setSecurityManager(original);
}
}
@SuppressWarnings("unused")
private static final class ClassWithPrivateFinalFields {
private final String a;