Question

I am trying to write my own bean utils converter so that I can export my object to a plain text file

I have the main class

 public class BeanUtilsTest {
    public static void main(String[] args) {
        try{
        MyObject myObject = new MyObject();
        myObject.setId(3l);
        myObject.setName("My Name");

        ConvertUtilsBean cub = new ConvertUtilsBean();
        cub.deregister(String.class);
        cub.register(new MyStringConverter(), String.class);
        cub.deregister(Long.class);
        cub.register(new MyLongConverter(), Long.class);

        System.out.println(cub.lookup(String.class));
        System.out.println(cub.lookup(Long.class));

        BeanUtilsBean bub = new BeanUtilsBean(cub, new PropertyUtilsBean());

        String name = bub.getProperty(myObject, "name");
        System.out.println(name);
        String id = bub.getProperty(myObject, "id");
        System.out.println(id);
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

The Long Converter

public class MyLongConverter implements Converter{

    @Override
    public Object convert(Class clazz, Object value) {
        System.out.println("Long convert");
        return value.toString()+"l";
    }

}

The String Converter

public class MyStringConverter implements Converter{

    @Override
    public Object convert(Class clazz, Object value) {
        System.out.println("String convert");
        return value.toString()+":";
    }
}

Finally my object

public class MyObject {
    Long id; 
    String name;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

The Output

String convert
My Name:
String convert
3:

I was expecting the id will go through MyLongConverter, but it seems it is still going thru the String one. Why and how can I fix this?

Please advise Thanks

Was it helpful?

Solution

String id = bub.getProperty(myObject, "id");

Above getProperty function in BeanUtilBean class has to return String representation of the property you requested, regardless of what format the property is defined. So, it will always use String converter (MyStringConverter).

Since the destination type here is always String, MyLongConverter will never be used.

Instead, MyStringConverter should inspect the type of the value parameter and accordingly convert it to String.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top