You can't do it directly, you should provide your own way to check this. Eg.

class MyClass {
  Object attr1, attr2, attr3;

  public boolean isValid() {
    return attr1 != null && attr2 != null && attr3 != null;
  }
}

Or make all fields final and initialize them in constructors so that you can be sure that everything is initialized.

Answer from Jack on Stack Overflow
🌐
Medium
tamerardal.medium.com › simplify-null-checks-in-java-writing-clean-code-with-apache-commons-lang-3-e7d3aea207bd
Simplify Null Checks in Java: Writing Clean Code with Apache Commons Lang 3 | by Tamer Ardal | Medium
September 18, 2024 - In Java, null checks are generally done using == or !=. In addition, if we want to do an empty check, our condition will look like the following.
🌐
Java Guides
javaguides.net › 2024 › 05 › java-check-if-object-is-null-or-empty.html
Java: Check If Object Is Null or Empty
May 29, 2024 - This guide will cover various ways to check if different types of objects (like String, Collection, Map, and custom objects) are null or empty.
🌐
Delft Stack
delftstack.com › home › howto › java › java check if object is null
How to Check if an Object Is Null in Java | Delft Stack
February 12, 2024 - The equals method, while primarily designed for equality checks, can be employed for null checks with caution, as it introduces the risk of NullPointerException. The Optional class, introduced in Java 8, offers an elegant and functional programming-style solution, encapsulating null-checking logic and promoting safer code.
🌐
LabEx
labex.io › tutorials › java-how-to-check-if-an-object-is-null-in-java-560011
How to Check If an Object Is Null in Java | LabEx
Optional without value is empty. Using ifPresent: Hello from Optional! Using orElse: Default Message · This output demonstrates how Optional can be used to handle the presence or absence of values more explicitly and safely compared to traditional null checks.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
April 8, 2019 - Java 8 introduced a new Optional API in the language. This offers a better contract for handling optional values compared to null. Let’s see how Optional takes away the need for null checks: public Optional<Object> process(boolean processed) { String response = doSomething(processed); if (response == null) { return Optional.empty(); } return Optional.of(response); } private String doSomething(boolean processed) { if (processed) { return "passed"; } else { return null; } } By returning an Optional, as shown above, the process method makes it clear to the caller that the response can be empty and needs to be handled at compile time.
🌐
Baeldung
baeldung.com › home › java › core java › check if all the variables of an object are null
Check If All the Variables of an Object Are Null | Baeldung
January 8, 2024 - Checking for null variables in our programs is helpful to avoid unexpected errors like IllegalArgumentException or a NullPointerException. When we try to access any member (field or method) of a null object, Java throws a NullPointerException.
🌐
Educative
educative.io › answers › what-is-objectutilsisempty-in-java
What is ObjectUtils.isEmpty in Java?
System.out.println("The output of ObjectUtils.isEmpty() when an empty set is passed is " + ObjectUtils.isEmpty(input)); ... System.out.println("The output of ObjectUtils.isEmpty() when an object of custom class is passed is " + ObjectUtils....
Find elsewhere
🌐
Java2Blog
java2blog.com › home › core java › java basics › check if object is null in java
Check if Object Is Null in Java - Java2Blog
November 29, 2023 - The == operator is the most efficient for single objects, while utility methods from Java 8 and external libraries provide more readability and functionality at a slightly higher performance cost.
🌐
Coderanch
coderanch.com › t › 399530 › java › check-Object-empty
How can i check if an Object[][] is empty (Beginning Java forum at Coderanch)
In this case you just check for a null reference: 2) The array has length 0. The check is quite similar to the above: 3) The subarrays are all null or length 0. In this case you have to check each subarray similar to 1 or 2 above. 4) The individual elements in the array are set to null. In this case, you need to check each individual element. So what do you mean by "empty"?
🌐
Linux Hint
linuxhint.com › check-object-is-null-java
How to Check if an Object is Null in Java
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
Top answer
1 of 3
13

Method overloading can make your implementations more efficient and cleaner:

public static boolean isEmpty(Collection obj) {
    return obj == null || obj.isEmpty();
}

public static boolean isEmpty(String string) {
    return string == null || string.trim().isEmpty();
}

public static boolean isEmpty(Object obj) {
    return obj == null || obj.toString().trim().isEmpty();
}

The Collection version is as efficient as possible.

The String version would be more efficient without the trimming. It would be best to trim your strings as soon you see them, long before they reach this call. If you can review the callers and make sure that the strings are always trimmed at their origins, then you can remove .trim() for best performance.

The Object version can be inefficient, depending on the toString implementation of the objects that will be passed to it, and because of the trimming.

I removed the comparison with null from there, because it seems pointless to me. I mean, a class whose toString method says "null" would seem very very odd.

In any case, you don't really want the Object version to be called, at all. Most importantly because it probably won't even work. Take for example an empty Map. Its toString method returns the string {}, which won't match your conditions of emptiness. (For this type you should definitely add isEmpty(Map<?, ?> map) to benefit from its isEmpty method.)

If performance is so critical, then add more overloaded implementations for all other types that you care about, for example:

public static boolean isEmpty(Something obj) {
    return obj == null || obj.isEmpty();
}

Finally, especially when something is so important, you definitely want to unit test it, for example:

@Test
public void testEmptyObject() {
    assertTrue(isEmpty((Object) null));
    assertFalse(isEmpty(new Object()));
}

@Test
public void testEmptyString() {
    assertFalse(isEmpty("hello"));
    assertTrue(isEmpty(""));
    assertTrue(isEmpty(" "));
    assertTrue(isEmpty((Object) null));
}

@Test
public void testEmptySet() {
    assertFalse(isEmpty(new HashSet<String>(Arrays.asList("hello"))));
    assertTrue(isEmpty(new HashSet<String>()));
}

@Test
public void testEmptyMap() {
    Map<String, String> map = new HashMap<String, String>();
    assertTrue(isEmpty(map));
    map.put("hello", "hi");
    assertFalse(isEmpty(map));
}
2 of 3
9

Don't.

I mean. Don't use the same method for all kinds of objects.

This method does not make much sense to me.

This line smells. A lot.

if (obj instanceof Collection)
    return ((Collection<?>) obj).size() == 0;

Beware of instanceof operator.

I am sure that whatever it is that you are trying to do here, there are better ways to do it.

Java is a statically typed language, use the static types whenever possible. If you really don't know what type the object have, then I will provide another alternative below.


// is below line expensive?
final String s = String.valueOf(obj).trim();

That depends, on the implementation of the object's toString method.

The implementation of String.valueOf is:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

return s.length() == 0 || s.equalsIgnoreCase("null");

You have already checked for obj == null. The string will only be null when the object's toString method makes it so. And instead of s.length() == 0 you can use s.isEmpty() directly. (Although that is implemented as string length == 0


Do it differently

If possible, have the types of objects you're investigating implement an interface that provides an isEmpty method and let the object decide for itself if it is empty or not.

If that is not possible, you can use a dynamically created map with ways to determine whether or not the object is "empty".

Map<Class<?>, EmptyChecker> map = new HashMap<>();
map.put(String.class, new StringEmptyChecker());
map.put(Point.class, new PointEmptyChecker());

This is a kind of Strategy pattern.

Then to determine if an object is empty:

EmptyChecker checker = map.get(obj.getClass());
checker.isEmpty(obj);

The whole thing is kinda weird though, I can't really see a particular use-case for this kind of method.

🌐
Javatpoint
javatpoint.com › how-to-check-null-in-java
How to Check null in Java
How to Check null in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
Stack Abuse
stackabuse.com › java-check-if-string-is-null-empty-or-blank
Java: Check if String is Null, Empty or Blank
February 28, 2023 - We will be using the length() method, which returns the total number of characters in our string. String blankString = " "; if (blankString == null || blankString.length() == 0) System.out.println("This string is null or empty"); else System.out.println("This string is neither null nor empty");
🌐
Educative
educative.io › answers › what-is-objectsisnull-in-java
What is Objects.isNull in Java?
The method isNull is a static method of the Objects class in java that checks whether the input object reference supplied to it is null or not. If the passed object is null, then the method returns true.
🌐
Better Programming
betterprogramming.pub › checking-for-nulls-in-java-minimize-using-if-else-edae27016474
Checking for Nulls in Java? Minimize Using “If Else” | by Itır ...
January 26, 2022 - Checks that the specified object reference is not null and throws a customized NullPointerExceptionif it is.