public class CustomeConverter : TypeConverter{ public override bool CanConvertFrom( ITypeDescriptorContext context, Type sourceType){ return true; } public override object ConvertFrom( ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value){ return new TypeCunstomer() { Name = value.ToString() }; } } public class TypeObject{ public TypeCunstomer Name { get; set; } } public class TypeCunstomer{ public string Name { get; set; } }<object type="Spring.Objects.Factory.Config.CustomConverterConfigurer, Spring.Core"> <property name="CustomConverters"> <dictionary> <entry key="SpringBase.TypeCunstomer"> <object type="SpringBase.CustomeConverter"/> </entry> </dictionary> </property> </object> <object id="typeconvert" type="SpringBase.TypeObject,SpringBase"> <property name="Name" value="2"/> </object>
- 繼承中的CanConvertFrom方法是用於判斷可否轉換,ConvertFrom轉換的具體方法
package springdemo; import java.beans.PropertyEditorSupport; public class TypeObject { private TypeCunstomer name; public TypeCunstomer getName() { return name; } public void setName(TypeCunstomer name) { this.name = name; } } class TypeCunstomer { private String name; String getName() { return name; } void setName(String name) { this.name = name; } } class CustomeConverter extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { TypeCunstomer val=new TypeCunstomer(); val.setName(text+"Convent"); this.setValue(val); } }<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="springdemo.TypeCunstomer"> <bean class="springdemo.CustomeConverter" /> </entry> </map> </property> </bean> <bean id="typeObject" class="springdemo.TypeObject"> <property name="name" value="1"/> </bean>
- 重寫setAsText方法,其中setValue的參數爲object
java和Csharp的共同點 html
- 配置文件中的dictionary|map標籤設置的key爲要轉換的類型,值爲轉換的方法類
- 都是繼承一個對象,而後重寫方法來自定義類型的轉換