简体   繁体   English

如何在Java中绑定通用类型以仅接受Integer和Double

[英]How to bound generic type in java to only accept Integer and double

private <T extends Number> T method(T param){...}

This will accept AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short. 这将接受AtomicInteger,AtomicLong,BigDecimal,BigInteger,Byte,Double,Float,Integer,Long和Short。

I want to only accept Double, Integer, Float. 我只想接受Double,Integer,Float。

You can't bound the generic type like this, because Integer , Double and Float are final . 您不能像这样绑定通用类型,因为IntegerDoubleFloatfinal Therefore, they can't be extended. 因此,它们不能扩展。

You can overload three methods: 您可以重载三种方法:

private Integer method(Integer param){...}

private Double method(Double param){...}

private Float method(Float param){...}

I dont believe there is a way to do it via generics (since those types you wanted are siblings). 我不相信有一种方法可以通过泛型来实现(因为您想要的那些类型是兄弟姐妹)。

I would instead just overload the method to take in those different parameters. 相反,我只是重载该方法以接收那些不同的参数。 It will look the same to each client, and also, the compiler will give you an error if the client tried to call the method with a wrong type. 每个客户端看起来都一样,而且,如果客户端尝试使用错误的类型调用该方法,编译器也会给您一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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