对于传递的泛型参数,Array.newInstance上的nullpointerexception

时间:2015-04-14 14:27:14

标签: 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.getClass().getComponentType(), templates.size());
    for (int i = 0; i < templates.size(); i++) {
        array[i] = command.buildTemplate(templates.get(i));
    }
    return array;
}

我在那里叫它

@Override
public TemplateResponse buildTemplateResponse(List<NotificationTemplateDetails> templates, String offset,
    String perPage, String sort, String sortOrder, int total) {
    TemplateResponse templateResponse = new TemplateResponse();
    templateResponse.setItems(ResponseUtils.<NotificationTemplateDetails, Template>toArray(new ToTemplateCommand(), templates));
    templateResponse.setTotal(total);
    templateResponse.setRequest(buildRequestInformation(offset, perPage, sort, sortOrder));
    return templateResponse;
}

其中ToTemplateCommandITemplateCommand iterface

的实现
public class ToTemplateCommand implements ITemplateCommand<NotificationTemplateDetails, Template> {

    @Override
    public Template buildTemplate(NotificationTemplateDetails template) {
    ....

但我{/ 1}}

NullPointerException

线。

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] .... command参数都不为空。 有什么问题?

1 个答案:

答案 0 :(得分:3)

如果您看到getComponentType()的{​​{3}},则说明了......

  

返回表示组件类型的Class   阵列。如果此类不表示此方法的数组类   返回null。