Java getter и setter для datetime возвращает значение null

1

У меня есть основной класс, который вызывает класс CurrentDateTime для установки даты и времени:

Основной класс:

public static void main(String args[]) {

    CurrentDateTime currentDateTime = new CurrentDateTime();
    currentDateTime.processDateTime();

    LogTracer.start();
}

Класс CurrentDateTime имеет следующий код:

Класс CurrentDateTime

public class CurrentDateTime {

    private String date;
    private String time;

    public String getDate() { return date; }

    public void setDate(String date) { this.date = date; }

    public String getTime() { return this.time; }

    public void setTime(String time) { this.time = time; }

    public void processDateTime() {
        date  = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
        this.setDate(date);
        time  = new SimpleDateFormat("HH-mm-ss").format(Calendar.getInstance().getTime());
        this.setTime(time);
        System.out.println("PROCESS " + date + " : " + time);
    }

}

Другой класс, который является моим регистратором, попытается получить дату и время:

Класс LogTracer

public static void start() {

    CurrentDateTime currentDateTime = new CurrentDateTime();
    System.out.println("currentDateTime.getTime() " + currentDateTime.getTime());

    String logFilename = "Error_" + currentDateTime.getTime() + ".log";

    String logDir = ("C:/test/" + currentDateTime.getDate()
            + File.separator + currentDateTime.getTime() + File.separator + "log");
}

Насколько я понимаю, основной класс будет запускать processDateTime() из класса CurrentDateTime для установки даты и времени. Тогда класс LogTracer просто вызовет getter. Но sysout "currentDateTime.getTime()" всегда показывает нуль вместо того, чтобы получать правильную дату и время. Не похоже, чтобы понять, что не так с кодом?

SYSOUT:

PROCESS 2014-09-08 : 16-26-10
currentDateTime.getTime() null
  • 1
    Вы используете конструктор по умолчанию и никогда не присваиваете значение времени. Попробуйте вызвать setTime, передав значение, а затем вызвать getTime.
Теги:
datetime

4 ответа

2

вы получаете нуль, потому что ссылка на объект в вашем main отличается от вашего класса Logracer.

public static void main(String args[]) {

    //currentdatetime object #1
    CurrentDateTime currentDateTime = new CurrentDateTime();
    //gettime() and getdate() not null here
    currentDateTime.processDateTime();

    LogTracer.start();
}

public static void start() {

    //currentdatetime object #2 (new object)
    CurrentDateTime currentDateTime = new CurrentDateTime();
    //gettime and getdate null here must call currentDateTime.processDateTime();
    // or pass by reference
    System.out.println("currentDateTime.getTime() " + currentDateTime.getTime());

    String logFilename = "Error_" + currentDateTime.getTime() + ".log";

    String logDir = ("C:/test/" + currentDateTime.getDate()
            + File.separator + currentDateTime.getTime() + File.separator + "log");
}

новая функция main и start

public static void main(String args[]) {

    //currentdatetime object #1
    CurrentDateTime currentDateTime = new CurrentDateTime();
    currentDateTime.processDateTime();

    // pass object #1 to LogTracer.start();
    LogTracer.start(currentDateTime);
}

public static void start(CurrentDateTime currentDateTime) {

    //access the object that is in the parameter. same object with main method.
    System.out.println("currentDateTime.getTime() " + currentDateTime.getTime());

    String logFilename = "Error_" + currentDateTime.getTime() + ".log";

    String logDir = ("C:/test/" + currentDateTime.getDate()
            + File.separator + currentDateTime.getTime() + File.separator + "log");
}
1

Вы должны передать параметр

Основной класс:

public static void main(String args[]) {

    CurrentDateTime currentDateTime = new CurrentDateTime();
    currentDateTime.processDateTime();

    LogTracer.start(currentDateTime);
}

Класс LogTracer:

public static void start(CurrentDateTime currentDateTime) {

    System.out.println("currentDateTime.getTime() " + currentDateTime.getTime());

    String logFilename = "Error_" + currentDateTime.getTime() + ".log";

    String logDir = ("C:/test/" + currentDateTime.getDate()
            + File.separator + currentDateTime.getTime() + File.separator + "log");
}
0

В методе LogTracer.start() вы создаете пустой экземпляр класса CurrentDateTime. Это потому, что вы используете конструктор по умолчанию. Попытайтесь использовать некоторый сеттер CurrentDateTime или getter или создать другой конструктор, который принимает информацию о дате/времени как параметр.

0

Вы забыли вызвать метод processDateTime(), добавить конструктор в CurrentDateTime.java

public CurrentDateTime() {
        processDateTime();
    }

вывод

PROCESS 2014-09-08 : 14-15-09
PROCESS 2014-09-08 : 14-15-09
PROCESS 2014-09-08 : 14-15-09
currentDateTime.getTime() 14-15-09

Ещё вопросы

Сообщество Overcoder
Наверх
Меню