【问题标题】:constructor threw exception nested exception is java.lang.nullpointerexception构造函数抛出异常嵌套异常是 java.lang.nullpointerexception
【发布时间】:2017-11-07 08:57:44
【问题描述】:

你好,下面是场景

@Component   
public class DateFormatter() {

public String DateToString() {
   //some Logic; 
      }
    }

public class DataProvider{

@Resource("dateFormatter")
private DateFormatter dateFormatter;

public void test(){
  Date date = new Date();


    String formattedDate = this.dateFormatter(date);

  system.out.print("Formatted Date is :" + formattedDate);}
}

构造函数抛出异常嵌套异常是 java.lang.nullpointerexception 是我在控制台上看到的

【问题讨论】:

  • 没有堆栈跟踪吗?它应该告诉您哪个构造函数指向了空指针。此外,您在此处发布的代码均不包含可能为空指针的构造函数...
  • public class DateFormatter() { 首先是不可编译的
  • 请格式化您的代码,使其清晰易读。
  • 正是我对 DateFormatter 给我的空指针感到困惑
  • 请不要发布草率的代码。如果您需要准确的帮助,请在您的问题和代码中保持准确。

标签: java spring


【解决方案1】:

this.dateFormatter(date); 正在调用 DateFormatter 和 dateFormatter 并且它没有这样的方法,因为您的示例中的 dateFormatter 不是方法。

public String DateToString(Date date) {
    //some Logic;
    return "";
}

您不能在参数中调用 DateToString 方法,并且不要在方法声明中提供它。

public class DataProvider{

        private DateFormatter dateFormatter;

        public void test(){
            Date date = new Date();

            DateFormatter dateFormatter = new DateFormatter();
            String formattedDate = dateFormatter.DateToString(date);

            System.out.print("Formatted Date is :" + formattedDate);}
    }

或者你可以这样做: 公共类 DataProvider{

    private DateFormatter dateFormatter;

    public DataProvider(DateFormatter dateFormatter) {
        this.dateFormatter = dateFormatter;
    }

    public void test(){
        Date date = new Date();

        String formattedDate = dateFormatter.DateToString(date);

        System.out.print("Formatted Date is :" + formattedDate);}
}

您必须创建对象的实例才能调用方法。

【讨论】:

  • 对不起是this.dateFormatter.DateToString(date)
猜你喜欢
  • 1970-01-01
  • 2013-05-31
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多