У меня есть способ проверить получателя электронной почты.
В моем коде .map(Recipient::getId) выдает ошибку:
Non static method cannot be reference from a static context.
private Long verifyRecipient(Long recipientId) throws NotFoundException {
return Optional.ofNullable(recipientRepository.findById(recipientId))
.map(Recipient::getId)
.orElseThrow(()-> new NotFoundException("recipient with ID" + recipientId +
" was not found"));
}
Recipient класс:
@Entity
public class Recipient {
@Id
@GeneratedValue
private Long id;
@NotBlank
private String name;
@NotBlank
@Email
@Column(unique = true)
private String emailAddress;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
Я использую SpringBoot и H2 в базе данных памяти.
Так что у меня тоже есть интерфейс RecipientRepository:
public interface RecipientRepository extends JpaRepository<Recipient, Long> {}
Определение метода findById():
Optional<T> findById(ID var1);




Метод findById() уже возвращает Optional<T>, поэтому в этой ситуации вам не нужно оборачивать результат дополнительным Optional.ofNullable().
Собственно, строка:
Optional.ofNullable(recipientRepository.findById(recipientId));
возвращает Optional<Optional<Recipient>>, который является избыточным.
Вместо этого вы можете просто написать:
private Long verifyRecipient(Long recipientId) throws NotFoundException {
return recipientRepository.findById(recipientId)
.map(Recipient::getId)
.orElseThrow(() ->
new NotFoundException("Recipient with ID " + recipientId + " was not found"));
}
Если вы используете аналогичную логику со сборкой экземпляра, это будет действительным, поэтому я бы предположил, что
recipientRepository.findById(recipientId)не возвращаетRecipient, поэтому компилятор ожидает использовать методstatic getId(SomeClass), гдеSomeClass- это тип, возвращаемыйfindById.