Java 传递的泛型参数的Array.newInstance上的nullpointerexception

Java 传递的泛型参数的Array.newInstance上的nullpointerexception,java,generics,Java,Generics,我有这样的方法 @SuppressWarnings("unchecked") public static <T, K> K[] toArray(ITemplateCommand<T,K> command, List<T> templates) { if (null == templates) { return null; } K[] array = (K[]) Array.newInstance(templates.ge

我有这样的方法

@SuppressWarnings("unchecked")
public static <T, K> K[] toArray(ITemplateCommand<T,K> command, List<T> templates) {
    if (null == templates) {
        return null;
    }
    K[] array = (K[]) Array.newInstance(templates.getClass().getComponentType(), templates.size());
    for (int i = 0; i < templates.size(); i++) {
        array[i] = command.buildTemplate(templates.get(i));
    }
    return array;
}
但是我已经打开了
NullPointerException

K[] array = (K[]) Array.newInstance(templates.getClass().getComponentType(), templates.size());
线路

但是
命令
模板
参数都不为空。 有什么问题吗?

如果您看到for
getComponentType()

返回表示组件类型的
数组。如果此类不表示数组类,请使用此方法 返回null


检查
templates.getClass()
是否返回null它返回
(java.lang.Class)类java.util.ArrayList
。但是
componentType
返回null。因此,它似乎无法识别组件类型
templates.getClass()。getComponentType()
可能应该是
templates.getClass()
-还要注意,您的
toArray
方法非常容易测试,因此您应该能够通过单元测试隔离问题并解决它。我在Eclipse中使用了
显示
选项卡来识别问题。我明白了。我决定在名为
getClassOfK
command
类中添加额外的方法,它允许我获取
K
类并实例化它。但我不确定这个解决方案。不过,它现在起作用了。
public class ToTemplateCommand implements ITemplateCommand<NotificationTemplateDetails, Template> {

    @Override
    public Template buildTemplate(NotificationTemplateDetails template) {
    ....
K[] array = (K[]) Array.newInstance(templates.getClass().getComponentType(), templates.size());
java.lang.NullPointerException: null
        at java.lang.reflect.Array.newArray(Native Method) ~[na:1.7.0_21]
        at java.lang.reflect.Array.newInstance(Array.java:70) ~[na:1.7.0_21]
....