user100617
user100617

Reputation: 35

Java generics

Is it possible to make a method that will take anything, including objects, Integers etc? I have a method checking the value if it is null and I was thinking perhaps it could be done with generics instead of overloading. Unfortunately, trying

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

won't allow Integers as they extend Number not object. Is there a way?

Cheers

Upvotes: 1

Views: 416

Answers (5)

user85421
user85421

Reputation: 29680

Since Java 1.7 you can use the methods of 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.

Upvotes: 0

ebasconp
ebasconp

Reputation:

A

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

would work... but... what for?

Do you think that

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

is easier to write than

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

?

Consider you will doing a method invocation in the first case and that consumes [almost nothing, but it does] system resources with no logical advantage, to me.

Upvotes: 0

RedMage
RedMage

Reputation:

Actually there is a way to do this, but I wouldn't recommend it for your usage...

So, here is how to do this (and warning, it circumvents compile time type checking, so you open yourself up to run-time class-cast exceptions...)

Say you have a "getter" than can return multiple types - it can be declared as a generic type like so:

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

You can do the same for a 'setter':

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

Upvotes: 0

bruno conde
bruno conde

Reputation: 48265

I'm not sure what you are trying to do... If it's just checking if a object is null then you can simply do this:

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

Upvotes: 2

Valentin Rocher
Valentin Rocher

Reputation: 11669

Can't you just do nullChecking(Object value) ? If you just wanna test if it's null, it will work.

Upvotes: 6

Related Questions