Java generics

Is it possible to create a method that will accept anything, including objects, integers, etc.? I have a method to check a value if it is null, and I was thinking maybe it could be done using generics and not overloading. Unfortunately an attempt

nullChecking(Class<? extends Object> value){
...
}

      

will not allow integers as they extend Number not object. Is there a way?

Greetings

+1


a source to share


5 answers


Can't you do nullChecking(Object value)

? If you just want to check if it is null it will work.



+6


a source


I'm not sure what you are trying to do ... If it just checks if an object is null

, you can simply do this:



public static boolean nullChecking(Object obj) {
    return obj == null;
}

      

+2


a source


There is actually a way to do this, but I would not recommend it for your use ...

So here's how to do it (and warning, this bypasses compile-time type checking, so you open yourself up to exceptions when the class is executed at runtime ...)

Say you have a "getter" than multiple types can return - it can be declared as a generic type, for example:

public <X> X get(String propertyName) { ... }

      

You can do the same for the 'setter':

public <X> void set(String property, X value) { ... }

      

0


a source


AND

public <T> boolean isNull(T obj) { return obj == null; } 

      

will work ... but ... why?

Do you think

if (isNull(myObj)) { ... }

      

easier to write than

if (myObj == null) { .... }

      

?

Suppose you make a method call in the first case and that consumes (almost nothing, but it) system resources with no logical benefit, for me.

0


a source


Since Java 1.7 you can use methods java.util.Objects

:

public static <T> T requireNonNull(T obj)
public static <T> T requireNonNull(T obj, String message)
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier)

      

or just check their code.

0


a source







All Articles