How to make it so that it was impossible to pass NULL to the constructor?
- 2In the constructor of what? Own class or something else? In this formulation, the question is too general to specifically answer it. - Streletz
- 2You invent a crutch. More precisely, you have some kind of problem, and you want to solve it, forbidding to transmit null that there is a crutch. Describe a specific problem better - Vladyslav Matviienko
1 answer
According to the java specification, you can pass null to the constructor (and it’s not the essence that you can assign null to any constructor) and then refer to it and get NPE.
How to be?
1) Optional (java 8, or Guava) http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
Does not save from NPE. Java is a mandatory NPE check; at compile time javac cannot determine what NPE will occur, so Optional is a more convenient syntax for checking for null.
2) Do not write to java, but try Kotlin: https://kotlinlang.org/docs/reference/null-safety.html
On it, you either do not assign null, or you must initialize the object, or write the behavior to null, otherwise it will not compile.
- oneBeg to correct. Optional is a peculiar way of saying that the value contained in it has the right to be null, eg it can be the result of a query in the cache, and has no direct relation to the separation of grains. Specifically, in Java, the easiest way is either to make the first line
Objects.requireNonNull()(throw out NPE, but before someone starts working with the value), or manually check and throw out IllegalArgumentException. - etki