Syboos Commons BeanUtils converters - Create custom Converter

2010/04/13 19:30Update
TAGS: BeanUtils | Converter | Custom | annotation

How to create a custom converter.

It's easy to create yourself custom converter. It's all ..

1. Create custom converter annotation


eg.
ConvertSomething.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import my.converter.SomethingConverter;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@ConvertConstraint(convertdBy=SomethingConverter.class)
public @interface ConvertSomething {
    public String myproperty();
}


2. Create custom converter


eg.
SomethingConverter.java
import com.syboos.beanutils.converter.Converter;

public class SomethingConverter extends Converter {
    private String myproperty;

    public String getMyproperty() {
        return myproperty;
    }

    public void setMyproperty(String myproperty) {
        this.myproperty = myproperty;
    }

    /* (non-Javadoc)
     * @see com.syboos.beanutils.converter.Converter#convert(java.lang.Object)
     */
    @Override
    public Object convert(Object value) {
        //TODO convert value
        return null; //return the converted value
    }
}


3. How to use the custom converter


@ConvertSomething(myproperty="somevalue")
private Object myfield;

...

.

有关作者
Syboos.jp編集長システム設計や開発、保守運営などを行ってます。オープンソース技術に興味があります。

Sponsored Link


Comments

用户名 (required)

Email (will not be published) (required)

URL

Evaluation