Search in sources :

Example 1 with FailToCastObjectException

use of org.nutz.castor.FailToCastObjectException in project nutz by nutzam.

the class Number2Enum method cast.

@Override
public Enum cast(Number src, Class<?> toType, String... args) throws FailToCastObjectException {
    int v = src.intValue();
    Enum o = null;
    // 首先试图用采用该类型的 fromInt 的静态方法
    try {
        Method m = toType.getMethod("fromInt", int.class);
        if (Modifier.isStatic(m.getModifiers()) && toType.isAssignableFrom(m.getReturnType())) {
            o = (Enum) m.invoke(null, v);
        }
    } catch (Exception e) {
    }
    // 搞不定,则试图根据顺序号获取
    if (null == o)
        try {
            for (Field field : toType.getFields()) {
                if (field.getType() == toType) {
                    Enum em = (Enum) field.get(null);
                    if (em.ordinal() == v)
                        return em;
                }
            }
            throw Lang.makeThrow(FailToCastObjectException.class, "Can NO find enum value in [%s] by int value '%d'", toType.getName(), src.intValue());
        } catch (Exception e2) {
            throw Lang.wrapThrow(e2, FailToCastObjectException.class);
        }
    return o;
}
Also used : Field(java.lang.reflect.Field) FailToCastObjectException(org.nutz.castor.FailToCastObjectException) Method(java.lang.reflect.Method) FailToCastObjectException(org.nutz.castor.FailToCastObjectException)

Example 2 with FailToCastObjectException

use of org.nutz.castor.FailToCastObjectException in project nutz by nutzam.

the class IocLoading method map2iobj.

@SuppressWarnings("unchecked")
public IocObject map2iobj(Map<String, Object> map) throws ObjectLoadException {
    final IocObject iobj = new IocObject();
    if (!isIocObject(map)) {
        for (Entry<String, Object> en : map.entrySet()) {
            IocField ifld = new IocField();
            ifld.setName(en.getKey());
            ifld.setValue(object2value(en.getValue()));
            iobj.addField(ifld);
        }
    //            if (log.isWarnEnabled()) // TODO 移除这种兼容性
    //                log.warn("Using *Declared* ioc-define (without type or events)!!! Pls use Standard Ioc-Define!!"
    //                            + " Bean will define as:\n"
    //                            + Json.toJson(iobj));
    } else {
        Object v = map.get("type");
        // type
        try {
            String typeName = (String) v;
            if (!Strings.isBlank(typeName)) {
                iobj.setType(Lang.loadClass(typeName));
            }
        } catch (Exception e) {
            throw E(e, "Wrong type name: '%s'", v);
        }
        // singleton
        try {
            v = map.get("singleton");
            if (null != v)
                iobj.setSingleton(Castors.me().castTo(v, boolean.class));
        } catch (FailToCastObjectException e) {
            throw E(e, "Wrong singleton: '%s'", v);
        }
        // scope
        v = map.get("scope");
        if (null != v)
            iobj.setScope(v.toString());
        // events
        try {
            v = map.get("events");
            if (null != v) {
                IocEventSet ies = Lang.map2Object((Map<?, ?>) v, IocEventSet.class);
                iobj.setEvents(ies);
            }
        } catch (Exception e) {
            throw E(e, "Wrong events: '%s'", v);
        }
        // args
        try {
            v = map.get("args");
            if (null != v) {
                Lang.each(v, new Each<Object>() {

                    public void invoke(int i, Object ele, int length) {
                        iobj.addArg(object2value(ele));
                    }
                });
            }
        } catch (Exception e) {
            throw E(e, "Wrong args: '%s'", v);
        }
        // fields
        try {
            v = map.get("fields");
            if (null != v) {
                Map<String, Object> fields = (Map<String, Object>) v;
                for (Entry<String, Object> en : fields.entrySet()) {
                    IocField ifld = new IocField();
                    ifld.setName(en.getKey());
                    ifld.setValue(object2value(en.getValue()));
                    iobj.addField(ifld);
                }
            }
        } catch (Exception e) {
            throw E(e, "Wrong args: '%s'", v);
        }
        // factory方法
        v = map.get("factory");
        if (v != null && !Strings.isBlank(v.toString())) {
            iobj.setFactory(v.toString());
        }
    }
    return iobj;
}
Also used : IocEventSet(org.nutz.ioc.meta.IocEventSet) FailToCastObjectException(org.nutz.castor.FailToCastObjectException) IocObject(org.nutz.ioc.meta.IocObject) Iocs.isIocObject(org.nutz.ioc.Iocs.isIocObject) IocField(org.nutz.ioc.meta.IocField) IocObject(org.nutz.ioc.meta.IocObject) Iocs.isIocObject(org.nutz.ioc.Iocs.isIocObject) HashMap(java.util.HashMap) Map(java.util.Map) FailToCastObjectException(org.nutz.castor.FailToCastObjectException)

Example 3 with FailToCastObjectException

use of org.nutz.castor.FailToCastObjectException in project nutz by nutzam.

the class Lang method map2Object.

/**
     * 根据一个 Map,和给定的对象类型,创建一个新的 JAVA 对象
     *
     * @param src
     *            Map 对象
     * @param toType
     *            JAVA 对象类型
     * @return JAVA 对象
     * @throws FailToCastObjectException
     */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T map2Object(Map<?, ?> src, Class<T> toType) throws FailToCastObjectException {
    if (null == toType)
        throw new FailToCastObjectException("target type is Null");
    // 类型相同
    if (toType == Map.class)
        return (T) src;
    // 也是一种 Map
    if (Map.class.isAssignableFrom(toType)) {
        Map map;
        try {
            map = (Map) toType.newInstance();
            map.putAll(src);
            return (T) map;
        } catch (Exception e) {
            throw new FailToCastObjectException("target type fail to born!", unwrapThrow(e));
        }
    }
    // 数组
    if (toType.isArray())
        return (T) Lang.collection2array(src.values(), toType.getComponentType());
    // List
    if (List.class == toType) {
        return (T) Lang.collection2list(src.values());
    }
    // POJO
    Mirror<T> mirror = Mirror.me(toType);
    T obj = mirror.born();
    for (Field field : mirror.getFields()) {
        Object v = null;
        if (!Lang.isAndroid && field.isAnnotationPresent(Column.class)) {
            String cv = field.getAnnotation(Column.class).value();
            v = src.get(cv);
        }
        if (null == v && src.containsKey(field.getName())) {
            v = src.get(field.getName());
        }
        if (null != v) {
            Class<?> ft = field.getType();
            Object vv = null;
            // 集合
            if (v instanceof Collection) {
                Collection c = (Collection) v;
                // 集合到数组
                if (ft.isArray()) {
                    vv = Lang.collection2array(c, ft.getComponentType());
                } else // 集合到集合
                {
                    // 创建
                    Collection newCol;
                    Class eleType = Mirror.getGenericTypes(field, 0);
                    if (ft == List.class) {
                        newCol = new ArrayList(c.size());
                    } else if (ft == Set.class) {
                        newCol = new LinkedHashSet();
                    } else {
                        try {
                            newCol = (Collection) ft.newInstance();
                        } catch (Exception e) {
                            throw Lang.wrapThrow(e);
                        }
                    }
                    // 赋值
                    for (Object ele : c) {
                        newCol.add(Castors.me().castTo(ele, eleType));
                    }
                    vv = newCol;
                }
            } else // Map
            if (v instanceof Map && Map.class.isAssignableFrom(ft)) {
                // 创建
                final Map map;
                // Map 接口
                if (ft == Map.class) {
                    map = new HashMap();
                } else // 自己特殊的 Map
                {
                    try {
                        map = (Map) ft.newInstance();
                    } catch (Exception e) {
                        throw new FailToCastObjectException("target type fail to born!", e);
                    }
                }
                // 赋值
                final Class<?> valType = Mirror.getGenericTypes(field, 1);
                each(v, new Each<Entry>() {

                    public void invoke(int i, Entry en, int length) {
                        map.put(en.getKey(), Castors.me().castTo(en.getValue(), valType));
                    }
                });
                vv = map;
            } else // 强制转换
            {
                vv = Castors.me().castTo(v, ft);
            }
            mirror.setValue(obj, field, vv);
        }
    }
    return obj;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) FailToCastObjectException(org.nutz.castor.FailToCastObjectException) ArrayList(java.util.ArrayList) FailToCastObjectException(org.nutz.castor.FailToCastObjectException) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Field(java.lang.reflect.Field) Entry(java.util.Map.Entry) Column(org.nutz.dao.entity.annotation.Column) Collection(java.util.Collection) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) NutMap(org.nutz.lang.util.NutMap)

Aggregations

FailToCastObjectException (org.nutz.castor.FailToCastObjectException)3 Field (java.lang.reflect.Field)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 Entry (java.util.Map.Entry)1 Set (java.util.Set)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 Column (org.nutz.dao.entity.annotation.Column)1 Iocs.isIocObject (org.nutz.ioc.Iocs.isIocObject)1 IocEventSet (org.nutz.ioc.meta.IocEventSet)1