下面的函数破解了“HttpURLConnection#methods”静态字段(通过 Java 反射)。我正在使用反射来对我的代码功能进行单元测试。我发现我们无法更改 JDK12 中的静态最终字段。我找到了一种使用 unsafe 的解决方案,但我不确定如何使用 unsafe 让此函数在 JDK12 中工作。
protected static void allowMethods(String... methods) {
try {
Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
Field modifiersField = Unsafe.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
methodsField.setAccessible(true);
String[] oldMethods = (String[]) methodsField.get(null);
Set<String> methodsSet = new LinkedHashSet<>(Arrays.asList(oldMethods));
methodsSet.addAll(Arrays.asList(methods));
String[] newMethods = methodsSet.toArray(new String[0]);
methodsField.set(null/*static field*/, newMethods);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
Run Code Online (Sandbox Code Playgroud)
这是上述代码的堆栈跟踪:
Caused by: java.lang.IllegalStateException: java.lang.NoSuchFieldException: modifiers
at pii.rest.call.RestUtils.allowMethods(RestUtils.java:75)
at pii.rest.call.JobAbort.<clinit>(JobAbort.java:39)
Caused by: java.lang.NoSuchFieldException: modifiers
at java.base/java.lang.Class.getDeclaredField(Class.java:2549) …Run Code Online (Sandbox Code Playgroud) 我正在将我的一个项目从 JDK8 迁移到 JDK11,但是其中一个单元测试失败了,尽管我想出了如何在 JDK11 中解决此问题的解决方案,但我不知道其背后的原因。如果有人向我解释这一变化,我真的很感激。这是适用于 JDK8 但不适用于 JDK11 的 HashSet:
Set<String> func(Properties p, String s) {
Set<String> set = p.stringPropertyNames();
set.removeIf(s -> !s.startsWith(s));
return set;
}
Run Code Online (Sandbox Code Playgroud)
我不得不像这样更改 HashSet 初始化以使我的测试运行并通过 JDK11:
Set<String> set = new HashSet<>(p.stringPropertyNames());
Run Code Online (Sandbox Code Playgroud)
我不明白为什么我必须在 JDK11 中像这样更改初始化,此更改是否打算在 JDK11 中使用?
错误堆栈跟踪:
null
java.lang.UnsupportedOperationException
at java.base/java.util.Collections$UnmodifiableCollection.removeIf(Collections.java:1089)
Run Code Online (Sandbox Code Playgroud) java ×2
collections ×1
hashset ×1
java-11 ×1
java-8 ×1
reflection ×1
static-block ×1
unit-testing ×1