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
a source to share
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) { ... }
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.
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.
a source to share