1 16 17 package org.springframework.beans.propertyeditors; 18 19 import java.beans.PropertyEditorSupport ; 20 21 import org.springframework.util.StringUtils; 22 23 42 public class CharacterEditor extends PropertyEditorSupport { 43 44 47 private static final String UNICODE_PREFIX = "\\u"; 48 49 52 private static final int UNICODE_LENGTH = 6; 53 54 55 private final boolean allowEmpty; 56 57 58 67 public CharacterEditor(boolean allowEmpty) { 68 this.allowEmpty = allowEmpty; 69 } 70 71 72 public void setAsText(String text) throws IllegalArgumentException { 73 if (this.allowEmpty && !StringUtils.hasText(text)) { 74 setValue(null); 76 } 77 else if (text == null) { 78 throw new IllegalArgumentException ("null String cannot be converted to char type"); 79 } 80 else if (isUnicodeCharacterSequence(text)) { 81 setAsUnicode(text); 82 } 83 else if (text.length() != 1) { 84 throw new IllegalArgumentException ("String [" + text + "] with length " + 85 text.length() + " cannot be converted to char type"); 86 } 87 else { 88 setValue(new Character (text.charAt(0))); 89 } 90 } 91 92 public String getAsText() { 93 Object value = getValue(); 94 return (value != null ? value.toString() : ""); 95 } 96 97 98 private void setAsUnicode(String text) { 99 int code = Integer.parseInt(text.substring(UNICODE_PREFIX.length()), 16); 100 setValue(new Character ((char) code)); 101 } 102 103 104 private static boolean isUnicodeCharacterSequence(String sequence) { 105 return sequence.startsWith(UNICODE_PREFIX) 106 && sequence.length() == UNICODE_LENGTH; 107 } 108 109 } 110 | Popular Tags |