问题描述
我完全被下面的堆栈跟踪弄得一团糟......看起来它是由 String
实例引起的,它在内部具有 null
字符数组.撇开反射不谈,在java中是否有任何合法"的方式来获得这样的 String
实例?
I'm completely riddled with the following stacktrace... Looks like it is caused by the String
instance which has null
char array internally. Putting aside reflection, is there any "legal" way to get such String
instance in java?
Caused by: java.lang.NullPointerException: null
at java.lang.String.length(String.java:611) ~[na:1.8.0_31]
at org.apache.commons.lang.StringUtils.isEmpty(StringUtils.java:195) ~[commons-lang-2.6.jar:2.6]
推荐答案
如果 合法 是指使用 String
API 公开的构造函数和方法,那么,不,不可能重现这样的异常.
If by legal you mean by using the constructors and methods exposed by the String
API, then, no, it is not possible to reproduce such an exception.
有一些方法可以实例化跳过构造函数和初始值设定项的类.sun.misc.Unsafe
提供了这样一个实用程序,allocateInstance
.
There are ways to instantiate classes that will skip constructors and initializers. sun.misc.Unsafe
provides such a utility, allocateInstance
.
public static void main(String[] args) throws Exception {
String string = (String) getUnsafe().allocateInstance(String.class);
System.out.println(string.length());
}
@SuppressWarnings("restriction")
private static Unsafe getUnsafe() {
try {
Field singleoneInstanceField = Unsafe.class.getDeclaredField("theUnsafe");
singleoneInstanceField.setAccessible(true);
return (Unsafe) singleoneInstanceField.get(null);
} catch (Exception e) {
}
return null;
}
在这种情况下,String
的value
字段将保持为null
,并且在调用时会出现NullPointerException
length()
.
In this case, the value
field of String
will remain null
and the NullPointerException
will occur when invoking length()
.
同样,一些使用字节码操作的代理库可以在创建代理子类时省略对 super()
的调用,从而有效地跳过初始化.这是一个相关问题,其中模拟未能正确初始化ArrayList
的支持数组.
Similarly, some proxying libraries that use byte code manipulation can omit an invocation to super()
when creating proxy subclasses, effectively skipping initialization. Here's a related question where mocking failed to properly initialize an ArrayList
's backing array.
这篇关于java.lang.String.length 处的 NullPointerException(String.java:611)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!