简体   繁体   English

如何从具有泛型类型的方法输入和返回值?

[英]How to input and return values from a method with generic types?

I'm trying to create the method deNull() to check input values. 我正在尝试创建方法deNull()来检查输入值。 These input value might be String, int, double, Timestamp. 这些输入值可能是String,int,double,Timestamp。 Therefore, I create the method with generics types. 因此,我创建了具有泛型类型的方法。

If the input value is null, then it will return ""; 如果输入值为空,则将返回“”;

If the input value is not null, then return the original value. 如果输入值不为null,则返回原始值。

My code is as below: 我的代码如下:

public static <T> T deNull(T value){
    if(value == null ){
        return "";
    } else {
        return value;
    }
}   

However, this method freaks out at line 3 and shows Type mismatch: Cannot convert from String to T. 但是,此方法在第3行出现异常,并显示类型不匹配:无法从String转换为T。

How should I amend this method to make it run as expected ? 我应该如何修改此方法以使其按预期运行?

int and double can not be null anyway, that leaves Timestamp and String as the only two options. intdouble都不能为null ,这使TimestampString成为仅有的两个选项。

In my opinion just write both methods without generics, not worth the hassle. 在我看来,只需编写两个没有泛型的方法,就不值得麻烦。

If you actually need it for more than two types, i would suggest changing the method to. 如果您实际上需要两种以上的类型,建议将方法更改为。

public static <T> T deNull(T value, T orElse){
    if(value == null ){
        return orElse;
    } else {
        return value;
    }
}   

String x = deNull( string, "");
Integer y = deNull( integer, 0);

(I would also suggest to change the method name to valueOrElse ) (我也建议将方法名称更改为valueOrElse

Since the return value is always a String type, decouple it from parameter type T. 由于返回值始终是String类型,因此将其与参数类型T分离。

public static <T> String deNull(T value) {
    if (value == null) {
        return "";
    } else {
        return value.toString();
    }
}

If the 'T' is String your line 3 is valid else it is fail. 如果“ T”为字符串,则您的第3行有效,否则失败。

return "";

If the T is Integer string cannot cast to Integer 如果T为整数,则字符串不能转换为整数

Integer a = 5;
String s = (String)a;//You cannot do like this

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

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