简体   繁体   中英

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

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

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;
}

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.

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) { ... }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM