简体   繁体   中英

How to make wildcard without double and float

I want to make generic, that can contain only Number without decimal part ( Integer , Long , Char , Byte , Short ). Is it possible? I understand that class Number is abstract , so everybody can write own implementation of every kind of numbers. But now I talk only about Oracle implementations.

No, it is not possible to realize this behaviour at compile time.

You can specify multiple type bounds in Java – for example T extends Integer & Long – but that means that T has to extend both Integer and Long .

Other languages – for example Ceylon – know the concept of type unions like Integer|Long|Char , but Java does not.

A possible workaround would be to use Number as a type bound and manually check the type at runtime, or to duplicate the public interface for the allowed types (eg write someMethod(Integer) and someMethod(Short) that call a private method that accepts a Number ). Anyway, think twice whether you really need this restriction.

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