I'm writing some code where I want to have a generic parameter, but it can't be a primitive. Is there a way to make sure a generic parameter to a function isn't a primitive?
For example, if I have the following function which checks if the parameter is an integer (using Integer
because int
doesn't have .getClass()
).:
public static final <E> int len(E e) {
Integer i = 0;
if (e.getClass() == i.getClass()) {
throw new IllegalArgumentException();
}
return 0;
}
If I wanted to keep going for every primitive, this function would be very long (no pun intended). In essence, can I prevent a primitive object from being passed into a function with generic parameters?
It's never a primitive. If a primitive is passed in, it will be autoboxed to the appropriate wrapper class, eg int
-> Integer
.
Regarding your statement int doesn't have .getClass() ...
Actually, int
does have a class: int.class
, but it is mainly used by the reflection api to represent method parameter types or return types of int
.
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.