gotch4
gotch4

Reputation: 13289

How to automatically convert property values from String in Java?

Suppose I've a bean that has many properties of many types like int, String, Date, etc... all primitive types of course. And I want to fill it with String representations of those values, without writing all the parsing code... how do I do that?

Upvotes: 0

Views: 3452

Answers (4)

Sualeh Fatehi
Sualeh Fatehi

Reputation: 4784

From what I understand of your question, you have a map of properties, for example:

name: "gotch4"
age: "21"
birthday: "7/21/2011"

and you want to create an instance of a hypothetical Person object, that has:

String getName()
int getAge()
Date getBirthday()

Apache Commons BeanUtils provides a good Java library to do this. Take a look at http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/package-summary.html#conversion

Upvotes: 1

brain
brain

Reputation: 5546

Bean frameworks like Spring do this for you. But if you want to write it yourself then you need use reflection to find the type required and then use the correct conversion code.

If you have a class like this:

public class MyBean {
    private int count;

    public void setCount(int count) {
        this.count = count;
    }
}

And an application context like this:

<beans>
    <bean id="myBean1" class="MyBean">
        <property name="count" value="3"/>
    </bean>
</beans>

Then it should all just work fine for you. Have a look at the docs for some more info, the examples are better than the docs though.

Upvotes: 1

Qwerky
Qwerky

Reputation: 18445

If you are trying to instantiate a bean with values from a property file (ie Strings), then the valueOf(String s) method is your friend. All primitive type wrapper classes (Short, Integer, Long, Float, Double, Boolean, Character, Byte and String) provide static factory methods called valueOf, taking a String argument.

Note that Date is not a primitive wrapper and does not fall into this category.

If you are interested I can post the code for a bean factory class I wrote that processes custom @Property annotations to create bean instances from property files.

Upvotes: 0

Jim
Jim

Reputation: 22656

You could use String.valueOf(). You can pass this whatever objects need converting and it will do the rest. Note if any objects are passed in they will need a suitable toString method implemented.

Upvotes: 0

Related Questions