为什么NPE使用DatatypeConverter的静态方法?

我已经盯着这个短代码太长了,并且不能为我的生活看到它如何在第6行抛出NullPointerException 。为什么NPE?

 class ConvertTest { public static void main(String[] args) throws Exception { byte[] b = "Ha".getBytes("UTF-8"); System.out.println("bytes: " + b.length); javax.xml.bind.DatatypeConverter.printBase64Binary(b); // NPE! } } 

产量

 bytes: 2 Exception in thread "main" java.lang.NullPointerException at javax.xml.bind.DatatypeConverter.printBase64Binary(DatatypeConverter.java:547) at ConvertTest.main(ConvertTest.java:6) Press any key to continue . . . 

更新

虽然许多错误报告都指向1.7变种,但我惊讶地看到Eclipse配置为使用1.6.0_32 TextPad发现版本为1.6.0-b105 (甚至没有意识到已经安装了!) 。

两个JRE都失败了NPE。

似乎JDK7中的JAXB中存在错误,正如Camel上的这个问题所certificate的那样:

https://issues.apache.org/jira/browse/CAMEL-4893

最终链接到这个问题https://github.com/javaee/jaxb-v2/issues/860在java.net上的JAXB项目中。

我不完全确定你是否遇到了同样的事情,但也许尝试使用JDK6和最新的JAXB版本,看看是否发生了相同的NPE。

没有环境的细节,我不能确定是这种情况,但如果您使用的是JAXB RI,那么您可能会遇到此JAXB错误所描述的问题: http : //java.net/jira/browse/JAXB -761

虽然该bug没有专门解决您遇到的问题(它与parseDate方法有关),但根本原因可能是相同的。 它在JAXB的2.2.1版本中被检测到,但可能在2.1.x版本中预先存在,而JAXB 2.1.1似乎是集成到1.6的最新版本(集成在1.6u14中)。

该问题表明它是通过JAXB 2.2.4解决的,它已集成到1.7中。

附加说明 – 在尝试使用parseBoolean时,记录了有关parseBoolean的NPE的相关问题,这可能是有意义的(虽然帮助不大,描述很短): http : //java.net/jira/browse/JAXB -902 这表明这仍然是一个持续的问题,具体取决于您是使用RI还是其他JAXB实现。

 public static String printBase64Binary( byte[] val ) { return theConverter.printBase64Binary( val ); } 

JAXB提供程序需要在第一次编组或解组操作之前的某个时刻调用setDatatypeConverter api(可能在调用JAXBContext.newInstance期间)。 此步骤是配置应用于执行打印和解析function的转换器所必需的

尝试先设置转换器

 /** * This method is for JAXB provider use only. * 

* JAXB Providers are required to call this method at some point before * allowing any of the JAXB client marshal or unmarshal operations to * occur. This is necessary to configure the datatype converter that * should be used to perform the print and parse conversions. * *

* Calling this api repeatedly will have no effect - the * DatatypeConverterInterface instance passed into the first invocation is * the one that will be used from then on. * * @param converter an instance of a class that implements the * DatatypeConverterInterface class - this parameter must not be null. * @throws IllegalArgumentException if the parameter is null */ public static void setDatatypeConverter( DatatypeConverterInterface converter ) { if( converter == null ) { throw new IllegalArgumentException( Messages.format( Messages.CONVERTER_MUST_NOT_BE_NULL ) ); } else if( theConverter == null ) { theConverter = converter; } }