-2

Note: The solution referenced by a couple of people here does not work for my problem...

I have a java.sql.Timestamp field that I want to format to a String in my getter. I'm using Lombok @Data at the beginning of the class. But when I override Lombok's getter with my own getter (to format the Timestamp), the field is always null. I don't see anything in the documentation to explain this behavior.

This block of code gives me the settlementDate as a Timestamp:

@Data
public class MyObject {
  public Timestamp settlementDate;
}

This block of code gives me a NPE, because the settlementDate is null. Hmm, it just occurred to me... Could it be because the return type of the getter is different from the member type?

@Data
public class MyObject {
  public Timestamp settlementDate;

  String getSettlementDate() {
    return new SimpleDateFormat("yyyy-MM-dd").format(tradeDate);
  }
}
CNDyson
  • 1,687
  • 7
  • 28
  • 63
  • 2
    See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Marcin Orlowski Apr 03 '17 at 12:23
  • 1
    How about this answer? [http://stackoverflow.com/questions/18139678/lombok-how-to-customise-getter-for-boolean-object-field](http://stackoverflow.com/questions/18139678/lombok-how-to-customise-getter-for-boolean-object-field) – KiteUp Apr 03 '17 at 12:29
  • I saw that, but wasn't really sure it applied to me... I'll try it though. – CNDyson Apr 03 '17 at 12:31
  • Possible duplicate of [Lombok how to customise getter for Boolean object field?](http://stackoverflow.com/questions/18139678/lombok-how-to-customise-getter-for-boolean-object-field) – Alex K Apr 03 '17 at 12:33
  • All you need - write one line of code `@Getter(AccessLevel.NONE) private Timestamp settlementDate;` Why you don't try it before ask, if you have seen that question? – user1516873 Apr 03 '17 at 12:34
  • Because I didn't think it applied to my problem. – CNDyson Apr 03 '17 at 12:35
  • Adding the @Getter annotation made no difference. I still get an NPE when I try to invoke getSettlementDate(). – CNDyson Apr 03 '17 at 12:46

1 Answers1

1

There's definitely some Lombok-unrelated problem with your code. Some of the following holds:

  • Your field doesn't get set before the access.
  • It does, but gets overwritten with null later.
  • You're accessing it on a different thread without a visibility guarantee.

As recommended in the comments, you should create an SSCCE. I usually do, and most of the time, I cancel my question as it leads me to a solution.


Note that writing a getter returning a type unusable with the setter is a very bad idea.

maaartinus
  • 44,714
  • 32
  • 161
  • 320