문제

I need to set some properties of a JavaBean. I have a generic Map<String, String> where the first String is the Name of the property and the second one represents it's value.

Now if the map looks like this:

"greeting" : "Hello"
"cool" : "true"
"amount" : "42"

and my setters in the bean look like this:

public void setGreeting(String greeting);
public void setCool(boolean cool);
public void setAmount(int amount);

i need to set these properties generically like:

BeanUtils.setProperty(myBean, "amount", myMap.get("amount"));

so that BeanUtils finds the right method to use and converts the String to the right type. At most places in the API doc it says "No type conversion" but i found a lot of converters in the API doc so i assume that there must be a way of doing this.

How can i let BeanUtils find the right method without knowing its type?

도움이 되었습니까?

해결책

The javadoc says:

Set the specified property value, performing type conversions as required to conform to the type of the destination property.

So it should convert your values automatically.

다른 팁

According to the documentation of class ConvertUtilsBean, the types that you can convert from String or String[] to the destination type automatically are:

  • java.lang.BigDecimal (no default value)
  • java.lang.BigInteger (no default value)
  • boolean and java.lang.Boolean (default to false)
  • byte and java.lang.Byte (default to zero)
  • char and java.lang.Character (default to a space)
  • java.lang.Class (no default value)
  • double and java.lang.Double (default to zero)
  • float and java.lang.Float (default to zero)
  • int and java.lang.Integer (default to zero)
  • long and java.lang.Long (default to zero)
  • short and java.lang.Short (default to zero)
  • java.lang.String (default to null)
  • java.io.File (no default value)
  • java.net.URL (no default value)
  • java.sql.Date (no default value)
  • java.sql.Time (no default value)
  • java.sql.Timestamp (no default value)

You can find a good example in Convert Utils Demo if you need another converter or replace someone.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top