Close

Java - PropertyEditor Examples

Java 

creating custom PropertyEditor by extending com.sun.beans.editors.BooleanEditor. It's not recommended to extend com.sun.* classes for an official project but it's ok to use them for learning purpose.

package com.logicbig.example;

import com.sun.beans.editors.BooleanEditor;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;

public class OverridingDefaultEditorExample {

public static void main (String[] args) {
//overriding default jdk boolean editor
PropertyEditorManager.registerEditor(Boolean.class, CustomBooleanEditor.class);
PropertyEditor editor = PropertyEditorManager.findEditor(Boolean.class);
editor.setAsText("yes");
System.out.println(editor.getValue());
}

public static class CustomBooleanEditor extends BooleanEditor {
@Override
public void setAsText (String text) throws IllegalArgumentException {
if ("yes".equalsIgnoreCase(text)) {
super.setAsText("true");
} else if ("no".equalsIgnoreCase(text)) {
super.setAsText("false");
} else {
super.setAsText(text);
}
}
}
}




Creating a custom editor and registering it with custom BeanInfo implementation and override BeanInfo#getPropertyDescriptors.

package com.logicbig.example;

import com.sun.beans.editors.StringEditor;

import java.beans.*;

public class PropEditor {

public static void main (String[] args) {

PropertyEditor editor = PropertyEditorManager.findEditor(User.class);
editor.setAsText("Joe");
System.out.println(editor.getValue());
}

public static class UserBeanInfo extends SimpleBeanInfo {
private UserEditor userEditor = new UserEditor();

@Override
public PropertyDescriptor[] getPropertyDescriptors () {
try {
PropertyDescriptor propertyDescriptor
= new PropertyDescriptor("name", User.class) {
@Override
public PropertyEditor createPropertyEditor (Object bean) {
return userEditor;
}
};

return new PropertyDescriptor[]{propertyDescriptor};

} catch (IntrospectionException e) {
throw new RuntimeException(e);
}
}
}

public static class UserEditor extends StringEditor {

@Override
public String getAsText () {
User user = (User) getValue();
return user.getName();
}

@Override
public void setAsText (String s) {
User user = new User();
user.setName(s);
setValue(user);
}
}

public static class User {
private String name;


public String getName () {
return name;
}

public void setName (String name) {
this.name = name;
}

@Override
public String toString () {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
}

Output:

User{name='Joe'}




See Also