在Java中构建通用的初始化函数 [英] building a generic initializer function in java

查看:88
本文介绍了在Java中构建通用的初始化函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提供一个函数,该函数可以让我传递任何对象和默认值,如果该对象不能转换为默认值的类型,则应返回该默认值。如果对象为null,则还应该返回默认值。



应按以下方式使用:

  Integer myVar = ConversionHelper.initialize( 123,0)//应该返回Integer(123)
Integer myVar = ConversionHelper.initialize( hello,0)//应该返回Integer(0)

,依此类推



我尝试了以下代码:

  public static< T> T initialize(Object o,T def){
T ret;

try {
ret =(T)o;
} catch(Exception e){
ret = def;
}

return ret == null吗? def:ret;
}

,但是它无法进行基本转换,例如将Integer转换为String。 / p>

编辑:采纳了答案中的许多建议,现在我正在寻找一种无需一系列if .. elseif ... elseif和我的答案中出现的try catch块

解决方案

通配符仅对 parameters 类型有效作为类型。正如您所注意到的,在这种情况下,普通的 Object 也是一样。



另一个有效的签名是:

 公共静态< IN,OUT> OUT初始化(IN o,默认为OUT){...} 

您的情况,因为泛型类型是不受限制的。



关于在try / catch中使用强制转换的转换策略,我不确定。



编辑:,正如您所发现的那样,除最简单的数据转换。您可能需要根据输入和输出类型实现到适当的解析方法调用的映射。



EDIT2:作为示例面对,这是某人为我正在进行的项目编写的数据转换方法:

  public static< T> T mapValueString(String valueString,Class< T> targetType){

if(valueString == null){
返回null;
}
else if(targetType.equals(String.class)){
return(T)valueString;
}
else if(targetType.equals(Date.class)){
return(T)MyDateTime.parseDate(valueString);
}
else if(targetType.equals(Timestamp.class)){
return(T)MyDateTime.parseTimestamp(valueString);
}
else if(targetType.equals(Boolean.class)){
String upperVal = valueString.toUpperCase();
if(upperVal.startsWith( T)){
return(T)Boolean.TRUE;
}
else if(upperVal.startsWith( F)){
return(T)Boolean.FALSE;
}
else {
throw new RuntimeException(未能将值字符串解析为布尔对象。字符串为 + valueString +。);
}
}
else if(targetType.equals(Integer.class)){
整数i;
try {
i = Integer.parseInt(valueString);
}
catch(NumberFormatException nfe){
抛出新的RuntimeException(未能将值字符串解析为Integer对象。字符串为 + valueString +。,nfe);
}
收益(T)i;
}
else if(targetType.equals(Long.class)){
Long l;
try {
l = Long.parseLong(valueString);
}
catch(NumberFormatException nfe){
抛出新的RuntimeException(未能将值字符串解析为Long对象。字符串为 + valueString +。,nfe);
}
回报(T)l;
}
else if(targetType.equals(Double.class)){
Double d;
try {
d = Double.parseDouble(valueString);
}
catch(NumberFormatException nfe){
抛出new RuntimeException(未能将值字符串解析为Double对象。字符串为 + valueString +。,nfe);
}
收益(T)d;
}
else {
throw new RuntimeException(不支持的Java类型 + targetType.getName()+。);
}
}

请注意,这仅用于映射字符串 T ,您要在其中将 T1 映射到 T2 。有没有更好的办法?也许。 SO可以帮助您找到正确的策略吗?当然,但是您可以根据自己的情况提出正确的问题。



EDIT3: Apache Commons的beanutils.converters 可能会有所帮助。不过我还没有尝试过,所以我无法评论。


I'm trying to come up with a function that lets me pass in any object and a default value, and if the object cannot be casted to the type of the default value, it should return that default value. If the object is null, it should also return the default value.

It should be used like this:

Integer myVar = ConversionHelper.initialize( "123", 0 ) // should return Integer(123)
Integer myVar = ConversionHelper.initialize( "hello", 0 ) // should return Integer(0)

and so on

I tried with the following code:

public static <T> T initialize(Object o, T def) {
    T ret;

    try {
        ret = (T) o;
    } catch (Exception e) {
        ret = def;
    }

    return ret==null ? def : ret;
}

but it fails with basic conversions, like casting an Integer to a String.

EDIT: took many of the suggestions from the answers, and now I'm looking for a way to do it without the series of if.. elseif... elseif and the try catch block that appears in my answer

解决方案

Wildcards are only valid as type parameters, not as types. In this case, as you noticed, plain old Object is just as good.

Another valid signature would be:

public static <IN, OUT> OUT initialize(IN o, OUT default) { ... }

But this looks to be unnecessary in your case, since the generic types are unbounded.

As for your strategy of conversion using casting within a try/catch, I'm not sure about it. Someone else should weigh in on that part.

EDIT: as you've discovered, casting is very limited when it comes to all but the simplest conversions of data. You may need to implement mappings to the appropriate parsing method calls depending on the in and out types.

EDIT2: as an example of what you're facing, here is a data conversion method somebody wrote for a project I'm on:

public static <T> T mapValueString(String valueString, Class<T> targetType) {

  if (valueString == null) {
     return null;
  }
  else if(targetType.equals(String.class)) {
     return (T)valueString;
  }
  else if (targetType.equals(Date.class)) {
     return (T)MyDateTime.parseDate(valueString);
  }
  else if (targetType.equals(Timestamp.class)) {
     return (T)MyDateTime.parseTimestamp(valueString);
  }
  else if (targetType.equals(Boolean.class)) {
     String upperVal = valueString.toUpperCase();
     if (upperVal.startsWith("T")) {
        return (T)Boolean.TRUE;
     }
     else if (upperVal.startsWith("F")) {
        return (T)Boolean.FALSE;
     }
     else {
        throw new RuntimeException("Failed to parse value string into Boolean object. String was " + valueString + ".");
     }
  }
  else if (targetType.equals(Integer.class)) {
     Integer i;
     try {
        i = Integer.parseInt(valueString);
     }
     catch (NumberFormatException nfe) {
        throw new RuntimeException("Failed to parse value string into Integer object. String was " + valueString + ".", nfe);
     }
     return (T)i;
  }
  else if (targetType.equals(Long.class)) {
    Long l;
    try {
       l = Long.parseLong(valueString);
    }
    catch (NumberFormatException nfe) {
       throw new RuntimeException("Failed to parse value string into Long object. String was " + valueString + ".", nfe);
    }
    return (T)l;
  }
  else if (targetType.equals(Double.class)) {
     Double d;
     try {
        d = Double.parseDouble(valueString);
     }
     catch (NumberFormatException nfe) {
        throw new RuntimeException("Failed to parse value string into Double object. String was " + valueString + ".", nfe);
     }
     return (T)d;
  }
  else {
     throw new RuntimeException("Unsupported java type " + targetType.getName() + ".");
  }
}

Note that this is only for mapping String to T, where you want to map T1 to T2. Is there a better way? Maybe. Can SO help you find the right strategy? Of course, but the ball's in your court to ask the right questions.

EDIT3: Apache Commons' beanutils.converters might be of help. I haven't tried it out though, so I can't remark on it.

这篇关于在Java中构建通用的初始化函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆