Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top