There is a class with methods. Code for example:

package helpers; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import java.util.Date; public class DateTimeHelper { /** * текущая дата */ private static final DateTime originalDate = new DateTime(new Date()); /** * получить текущую дату и время относительно запуска теста */ public DateTime getOriginalDate(){ return originalDate; } /** * Печать даты в требуемом формате * @param date дата которую надо напечатать * @param format формат печати * @return строку содержащую требуемую дату в требуемом формате */ public String printDateShortFormat(DateTime date,String format){ String pattern="yyyy"; switch (format){ case "standard": pattern = "dd.MM.yyyy' 'HH:mm"; break; case "full": // не задаём формат break; case "only-date": pattern = "dd.MM.yyyy"; break; case "only-time": pattern = "HH:mm"; break; default: throw new AssertionError("[ERROR] Не обрабатываемый формат"); } return DateTimeFormat.forPattern(pattern).print(date); } /** * Прибавление к дате дней * @param date дата * @param days количество дней добавляемых к дате * @return результат сложения */ public DateTime plusDays(DateTime date, int days){ return date.plusDays(days); } } 

I don't want to call methods like this

 dateTimeHelper.printDateShortFormat( dateTimeHelper.plusDays(dateTimeHelper.getOriginalDate(),5 ), "standard" ); 

How to describe this class so that you can call methods in a similar way (pseudocode): How can you realize the situation where the value is returned and the next method takes this value as a parameter through a dot? example:

 DateTimeHelper.getOriginalDate().plusDays(5).printDateShortFormat("standard") 

so generally possible?)

2 answers 2

This is called the fluent interface and is achieved by returning from the method of the object whose methods can be called further in the chain. Often the method returns a link to itself.

 public class Example { public Example someMethod() { System.out.println("Hello"); return this; } public Example anotherMethod() { System.out.println("World"); return this; } public static void main(String[] args) { Example obj = new Example(); obj.someMethod().anotherMethod(); } } 

UPDATE:

 import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeHelper { private static class DateWrapper { private LocalDateTime dateTime; private DateTimeFormatter formatter; public DateWrapper(LocalDateTime dateTime) { this.dateTime = dateTime; } public DateWrapper shortFormat(String format) { String pattern="yyyy"; switch (format) { case "standard": pattern = "dd.MM.yyyy' 'HH:mm"; break; case "full": // не задаём формат break; case "only-date": pattern = "dd.MM.yyyy"; break; case "only-time": pattern = "HH:mm"; break; default: throw new IllegalArgumentException("Неизвестный формат"); } formatter = DateTimeFormatter.ofPattern(pattern); return this; } public DateWrapper plusDays(int days) { dateTime = dateTime.plusDays(days); return this; } public void print() { if (formatter == null) throw new IllegalStateException("Не задан формат"); System.out.println(dateTime.format(formatter)); } } public static DateWrapper now() { return new DateWrapper(LocalDateTime.now()); } public static void main(String[] args) { DateTimeHelper.now() .plusDays(5) .shortFormat("standard") .print(); } } 
  • If you look at the sample code that I wrote in the question. How can one realize the situation where the value is returned and the following method takes a value as a parameter as a parameter? example: DateTimeHelper.getOriginalDate().plusDays(5).printDateShortFormat("standard") - sevnight
  • As I have already written, "it is achieved by returning from the method of the object whose methods can be called further in the chain." That is, for example, to return not LocalDate , but some LocalDateWrapper . - Sergey Gornostaev

Can. But for this you need some builder, which will update its fields in each initialization method and return itself (this), and in the last method (in your case of print) return the formatted value of the fields initialized earlier. I advise you to read about the Builder pattern. I also advise you to look at the classes LocalDate and LocalDateTime. Your utility methods (I would make them static) are very similar to what they already have.