1 12 package org.eclipse.core.internal.databinding.conversion; 13 14 import org.eclipse.core.databinding.BindingException; 15 import org.eclipse.core.databinding.conversion.IConverter; 16 17 20 public class IdentityConverter implements IConverter { 21 22 private Class fromType; 23 24 private Class toType; 25 26 29 public IdentityConverter(Class type) { 30 this.fromType = type; 31 this.toType = type; 32 } 33 34 38 public IdentityConverter(Class fromType, Class toType) { 39 this.fromType = fromType; 40 this.toType = toType; 41 } 42 43 private Class [][] primitiveMap = new Class [][] { 44 { Integer.TYPE, Integer .class }, { Short.TYPE, Short .class }, 45 { Long.TYPE, Long .class }, { Double.TYPE, Double .class }, 46 { Byte.TYPE, Byte .class }, { Float.TYPE, Float .class }, 47 { Boolean.TYPE, Boolean .class }, }; 48 49 54 public Object convert(Object source) { 55 if (toType.isPrimitive()) { 56 if (source == null) { 57 throw new BindingException("Cannot convert null to a primitive"); } 59 } 60 if (source != null) { 61 Class sourceClass = source.getClass(); 62 if (toType.isPrimitive() || sourceClass.isPrimitive()) { 63 if (sourceClass.equals(toType) 64 || isPrimitiveTypeMatchedWithBoxed(sourceClass, toType)) { 65 return source; 66 } 67 throw new BindingException( 68 "Boxed and unboxed types do not match"); } 70 if (!toType.isAssignableFrom(sourceClass)) { 71 throw new BindingException(sourceClass.getName() 72 + " is not assignable to " + toType.getName()); } 74 } 75 return source; 76 } 77 78 85 public boolean isPrimitiveTypeMatchedWithBoxed(Class sourceClass, 86 Class toClass) { 87 for (int i = 0; i < primitiveMap.length; i++) { 88 if (toClass.equals(primitiveMap[i][0]) 89 && sourceClass.equals(primitiveMap[i][1])) { 90 return true; 91 } 92 if (sourceClass.equals(primitiveMap[i][0]) 93 && toClass.equals(primitiveMap[i][1])) { 94 return true; 95 } 96 } 97 return false; 98 } 99 100 public Object getFromType() { 101 return fromType; 102 } 103 104 public Object getToType() { 105 return toType; 106 } 107 108 } 109 | Popular Tags |