Exemplo n.º 1
0
 public ValueAdaptor getAdaptor(MappingField ef) {
   Mirror<?> mirror = ef.getTypeMirror();
   // 为数字型枚举的特殊判断
   if (mirror.isEnum() && ColType.INT == ef.getColumnType()) return Jdbcs.Adaptor.asEnumInt;
   // 用普通逻辑返回适配器
   return Jdbcs.getAdaptor(mirror);
 }
Exemplo n.º 2
0
 /**
  * 根据一个字段名和字段类型获取 Setter
  *
  * @param fieldName 字段名
  * @param paramType 字段类型
  * @return 方法
  * @throws NoSuchMethodException 没找到 Setter
  */
 public Method getSetter(String fieldName, Class<?> paramType) throws NoSuchMethodException {
   try {
     String setterName = "set" + Strings.capitalize(fieldName);
     try {
       return klass.getMethod(setterName, paramType);
     } catch (Throwable e) {
       try {
         return klass.getMethod(fieldName, paramType);
       } catch (Throwable e1) {
         Mirror<?> type = Mirror.me(paramType);
         for (Method method : klass.getMethods()) {
           if (method.getParameterTypes().length == 1)
             if (method.getName().equals(setterName) || method.getName().equals(fieldName)) {
               if (null == paramType || type.canCastToDirectly(method.getParameterTypes()[0]))
                 return method;
             }
         }
         // 还是没有? 会不会是包装类型啊?
         if (!paramType.isPrimitive()) {
           Class<?> p = unWrapper();
           if (null != p) return getSetter(fieldName, p);
         }
         throw new RuntimeException();
       }
     }
   } catch (Throwable e) {
     throw Lang.makeThrow(
         NoSuchMethodException.class,
         "Fail to find setter for [%s]->[%s(%s)]",
         klass.getName(),
         fieldName,
         paramType.getName());
   }
 }
Exemplo n.º 3
0
Arquivo: Exps.java Projeto: sunyh/nutz
  public static SqlExpression create(String name, String op, Object value) {
    op = Strings.trim(op.toUpperCase());

    // NULL
    if (null == value) {
      SqlExpression re;
      // IS NULL
      if ("IS".equals(op) || "NOT IS".equals(op) || "IS NOT".equals(op)) {
        re = isNull(name);
      }
      // !!!
      else {
        throw Lang.makeThrow("null can only use 'IS' or 'NOT IS'");
      }
      return re.setNot(op.startsWith("NOT") || op.endsWith("NOT"));
    }
    // IN
    else if ("IN".equals(op) || "NOT IN".equals(op)) {
      Class<?> type = value.getClass();
      SqlExpression re;
      // 数组
      if (type.isArray()) {
        re = _evalRange((Mirror<?>) Mirror.me(type.getComponentType()), name, value);
      }
      // 集合
      else if (Collection.class.isAssignableFrom(type)) {
        Object first = Lang.first(value);
        if (null == first) return null;
        re = _evalRange((Mirror<?>) Mirror.me(first), name, value);
      }
      // Sql Range
      else {
        re = inSql(name, value.toString());
      }
      return re.setNot(op.startsWith("NOT"));
    }
    // LIKE || IS
    else if ("LIKE".equals(op) || "NOT LIKEs".equals(op)) {
      String v = value.toString();
      Like re;
      if (v.length() == 1) {
        re = like(name, v);
      } else {
        re = like(name, v.substring(1, v.length() - 1));
        re.left(v.substring(0, 1));
        re.right(v.substring(v.length() - 1, v.length()));
      }
      return re.ignoreCase(false).setNot(op.startsWith("NOT"));
    }
    // =
    else if ("=".equals(op)) {
      return eq(name, value);
    }
    // !=
    else if ("!=".equals(op) || "<>".equals(op)) { // TODO 检查一下,原本是&&, 明显永远成立
      return eq(name, value).setNot(true);
    }
    // Others
    return new SimpleExpression(name, op, value);
  }
Exemplo n.º 4
0
 /**
  * 根据Type生成Mirror, 如果type是 {@link ParameterizedType} 类型的对象<br>
  * 可以使用 getGenericsTypes() 方法取得它的泛型数组
  *
  * @param type
  * @return
  */
 @SuppressWarnings({"unchecked"})
 public static <T> Mirror<T> me(Type type) {
   if (null == type) {
     return null;
   }
   Mirror<T> mir = (Mirror<T>) Mirror.me(Lang.getTypeClass(type));
   mir.type = type;
   return mir;
 }
Exemplo n.º 5
0
 public <T> T toObject(Class<T> classOfT) {
   Mirror<T> mirror = Mirror.me(classOfT);
   T re = mirror.born();
   Entry current = head;
   while (current != null) {
     mirror.setValue(re, current.name, current.value);
     current = current.next;
   }
   return re;
 }
Exemplo n.º 6
0
 /**
  * @param type 目标类型
  * @return 判断当前对象是否能直接转换到目标类型,而不产生异常
  */
 public boolean canCastToDirectly(Class<?> type) {
   if (klass == type || type.isAssignableFrom(klass)) return true;
   if (klass.isPrimitive() && type.isPrimitive()) {
     if (this.isPrimitiveNumber() && Mirror.me(type).isPrimitiveNumber()) return true;
   }
   try {
     return Mirror.me(type).getWrapperClass() == this.getWrapperClass();
   } catch (Exception e) {
   }
   return false;
 }
Exemplo n.º 7
0
 /**
  * 构建DataSource,子类可覆盖. 如果存在Druid,则使用之,否则使用内置的SimpleDataSource
  *
  * @param props 配置信息
  * @return 目标DataSource
  */
 protected DataSource buildDataSource(Properties props) {
   if (druidFactoryClass != null) {
     log.debug("build DruidDataSource by props");
     Mirror<?> mirror = Mirror.me(druidFactoryClass);
     DataSource ds = (DataSource) mirror.invoke(null, "createDataSource", props);
     if (!props.containsKey("maxWait")) Mirror.me(ds).setValue(ds, "maxWait", 15 * 1000);
     return ds;
   }
   log.debug("build SimpleteDataSource by props");
   return SimpleDataSource.createDataSource(props);
 }
Exemplo n.º 8
0
  @SuppressWarnings("unchecked")
  public <T extends CommonManager> T copy() {
    String clazzName = this.getClass().getName().replace(ClassAgent.CLASSNAME_SUFFIX, "");

    try {
      Mirror<T> mirror = (Mirror<T>) Mirror.me(Class.forName(clazzName));
      return ClassUtil.copySameProperties(mirror.born(), this);
    } catch (ClassNotFoundException e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }
Exemplo n.º 9
0
 @SuppressWarnings("unchecked")
 private <F, T> Castor<F, T> find(Mirror<F> from, Class<T> toType) {
   Mirror<T> to = Mirror.me(toType, extractor);
   Class<?>[] fets = from.extractTypes();
   Class<?>[] tets = to.extractTypes();
   for (Class<?> ft : fets) {
     for (Class<?> tt : tets) {
       if (map.containsKey(Castor.fetchHash(ft, tt))) {
         return (Castor<F, T>) map.get(Castor.fetchHash(ft, tt));
       }
     }
   }
   return null;
 }
Exemplo n.º 10
0
 private static boolean doMatchMethodParamsType(Class<?>[] paramTypes, Class<?>[] methodArgTypes) {
   if (paramTypes.length == 0 && methodArgTypes.length == 0) return true;
   if (paramTypes.length == methodArgTypes.length) {
     for (int i = 0; i < paramTypes.length; i++)
       if (!Mirror.me(paramTypes[i]).canCastToDirectly((methodArgTypes[i]))) return false;
     return true;
   } else if (paramTypes.length + 1 == methodArgTypes.length) {
     if (!methodArgTypes[paramTypes.length].isArray()) return false;
     for (int i = 0; i < paramTypes.length; i++)
       if (!Mirror.me(paramTypes[i]).canCastToDirectly((methodArgTypes[i]))) return false;
     return true;
   }
   return false;
 }
Exemplo n.º 11
0
 /**
  * 当一个类使用<T,K>来定义泛型时,本方法返回类的一个字段的具体类型。
  *
  * @param me
  * @param field
  * @return
  */
 public static Type getFieldType(Mirror<?> me, Field field) {
   Type type = field.getGenericType();
   Type[] types = me.getGenericsTypes();
   if (type instanceof TypeVariable && types != null && types.length > 0) {
     Type[] tvs = me.getType().getTypeParameters();
     for (int i = 0; i < tvs.length; i++) {
       if (type.equals(tvs[i])) {
         type = me.getGenericsType(i);
         break;
       }
     }
   }
   return type;
 }
Exemplo n.º 12
0
 /**
  * 根据一个对象的字段 生成一个 Chain 对象
  *
  * <p>这个对象可以是一个 POJO 或者是一个 Map。
  *
  * <p>支持 FieldMatcher,即你可以通过 FieldMatcher 来指定你需要哪些字段加入 Chain
  *
  * @param obj 对象,可以是一个 POJO 或者是一个 Map
  * @param fm 指明可用字段,null 表示全部字段可用
  * @return Chain 对象,null 表示对象中没有可用字段
  * @see org.nutz.dao.FieldMatcher
  */
 public static Chain from(Object obj, FieldMatcher fm) {
   if (null == obj) return null;
   Chain c = null;
   /*
    * Is Map
    */
   if (obj instanceof Map<?, ?>) {
     for (Map.Entry<?, ?> en : ((Map<?, ?>) obj).entrySet()) {
       Object key = en.getKey();
       if (null == key) continue;
       String name = key.toString();
       if (null != fm && !fm.match(name)) continue;
       Object v = en.getValue();
       if (null != fm) {
         if (null == v) {
           if (fm.isIgnoreNull()) continue;
         } else if (fm.isIgnoreBlankStr() && v instanceof String) {
           if (Strings.isBlank((String) v)) continue;
         }
       }
       if (c == null) {
         c = Chain.make(name, v);
       } else {
         c = c.add(name, v);
       }
     }
   }
   /*
    * Is POJO
    */
   else {
     Mirror<?> mirror = Mirror.me(obj.getClass());
     for (Field f : mirror.getFields()) {
       if (null != fm && !fm.match(f.getName())) continue;
       Object v = mirror.getValue(obj, f.getName());
       if (null == v) {
         if (fm.isIgnoreNull()) continue;
       } else if (fm.isIgnoreBlankStr() && v instanceof String) {
         if (Strings.isBlank((String) v)) continue;
       }
       if (c == null) {
         c = Chain.make(f.getName(), v);
       } else {
         c = c.add(f.getName(), v);
       }
     }
   }
   return c;
 }
Exemplo n.º 13
0
 /**
  * 匹配一个函数声明的参数类型数组和一个调用参数数组
  *
  * @param paramTypes 函数声明参数数组
  * @param argTypes 调用参数数组
  * @return 匹配类型
  * @see org.nutz.lang.MatchType
  */
 public static MatchType matchParamTypes(Class<?>[] paramTypes, Class<?>[] argTypes) {
   int len = argTypes == null ? 0 : argTypes.length;
   if (len == 0 && paramTypes.length == 0) return MatchType.YES;
   if (paramTypes.length == len) {
     for (int i = 0; i < len; i++)
       if (!Mirror.me(argTypes[i]).canCastToDirectly((paramTypes[i]))) return MatchType.NO;
     return MatchType.YES;
   } else if (len + 1 == paramTypes.length) {
     if (!paramTypes[len].isArray()) return MatchType.NO;
     for (int i = 0; i < len; i++)
       if (!Mirror.me(argTypes[i]).canCastToDirectly((paramTypes[i]))) return MatchType.NO;
     return MatchType.LACK;
   }
   return MatchType.NO;
 }
Exemplo n.º 14
0
  protected String value2string(JsonEntityField jef, Object value) {

    Format df = jef.getDataFormat();
    if (df == null) {
      Mirror mirror = Mirror.me(value);
      if (value instanceof Date) {
        df = format.getDateFormat();
      } else if (mirror.isNumber()) {
        df = format.getNumberFormat();
      }
    }
    if (df != null) {
      return df.format(value);
    }
    return value.toString();
  }
Exemplo n.º 15
0
 /**
  * @param type 类型
  * @return 否为一个对象的外覆类
  */
 public boolean isWrapperOf(Class<?> type) {
   try {
     return Mirror.me(type).getWrapperClass() == klass;
   } catch (Exception e) {
   }
   return false;
 }
Exemplo n.º 16
0
 /**
  * 将一个数组变成 Map
  *
  * @param mapClass Map 的类型
  * @param array 数组
  * @param keyFieldName 采用集合中元素的哪个一个字段为键。
  * @return Map 对象
  */
 public static <T extends Map<Object, Object>> Map<?, ?> array2map(
     Class<T> mapClass, Object array, String keyFieldName) {
   if (null == array) return null;
   Map<Object, Object> map = createMap(mapClass);
   int len = Array.getLength(array);
   if (len > 0) {
     Object obj = Array.get(array, 0);
     Mirror<?> mirror = Mirror.me(obj.getClass());
     for (int i = 0; i < len; i++) {
       obj = Array.get(array, i);
       Object key = mirror.getValue(obj, keyFieldName);
       map.put(key, obj);
     }
   }
   return map;
 }
Exemplo n.º 17
0
 /**
  * 转换一个 POJO 从一个指定的类型到另外的类型
  *
  * @param src 源对象
  * @param fromType 源对象类型
  * @param toType 目标类型
  * @param args 转换时参数。有些 Castor 可能需要这个参数,比如 Array2Map
  * @return 目标对象
  * @throws FailToCastObjectException 如果没有找到转换器,或者转换失败
  */
 @SuppressWarnings({"unchecked", "rawtypes"})
 public <F, T> T cast(Object src, Class<F> fromType, Class<T> toType, String... args)
     throws FailToCastObjectException {
   if (null == src) {
     // 原生数据的默认值
     if (toType.isPrimitive()) {
       if (toType == int.class) return (T) Integer.valueOf(0);
       else if (toType == long.class) return (T) Long.valueOf(0L);
       else if (toType == byte.class) return (T) Byte.valueOf((byte) 0);
       else if (toType == short.class) return (T) Short.valueOf((short) 0);
       else if (toType == float.class) return (T) Float.valueOf(.0f);
       else if (toType == double.class) return (T) Double.valueOf(.0);
       else if (toType == boolean.class) return (T) Boolean.FALSE;
       else if (toType == char.class) return (T) Character.valueOf(' ');
       throw Lang.impossible();
     }
     // 是对象,直接返回 null
     return null;
   }
   if (fromType == toType || toType == null || fromType == null) return (T) src;
   if (fromType.getName().equals(toType.getName())) return (T) src;
   if (toType.isAssignableFrom(fromType)) return (T) src;
   Mirror<?> from = Mirror.me(fromType, extractor);
   if (from.canCastToDirectly(toType)) // Use language built-in cases
   return (T) src;
   Castor c = find(from, toType);
   if (null == c)
     throw new FailToCastObjectException(
         String.format(
             "Can not find castor for '%s'=>'%s' in (%d) because:\n%s",
             fromType.getName(), toType.getName(), map.size(), "Fail to find matched castor"));
   try {
     return (T) c.cast(src, toType, args);
   } catch (FailToCastObjectException e) {
     throw e;
   } catch (Exception e) {
     throw new FailToCastObjectException(
         String.format(
             "Fail to cast from <%s> to <%s> for {%s} because:\n%s:%s",
             fromType.getName(),
             toType.getName(),
             src,
             e.getClass().getSimpleName(),
             e.getMessage()),
         Lang.unwrapThrow(e));
   }
 }
Exemplo n.º 18
0
 /**
  * 将一个集合变成 Map。
  *
  * @param mapClass Map 的类型
  * @param coll 集合对象
  * @param keyFieldName 采用集合中元素的哪个一个字段为键。
  * @return Map 对象
  */
 public static <T extends Map<Object, Object>> Map<?, ?> collection2map(
     Class<T> mapClass, Collection<?> coll, String keyFieldName) {
   if (null == coll) return null;
   Map<Object, Object> map = createMap(mapClass);
   if (coll.size() > 0) {
     Iterator<?> it = coll.iterator();
     Object obj = it.next();
     Mirror<?> mirror = Mirror.me(obj.getClass());
     Object key = mirror.getValue(obj, keyFieldName);
     map.put(key, obj);
     for (; it.hasNext(); ) {
       obj = it.next();
       key = mirror.getValue(obj, keyFieldName);
       map.put(key, obj);
     }
   }
   return map;
 }
Exemplo n.º 19
0
 /**
  * 关闭本DaoUp,将关闭DataSource并将dao和dataSource置为null!!!
  *
  * <p><b>只能在程序关闭时调用,严禁在每次Dao操作后调用!!</b>
  */
 public synchronized void close() {
   if (dao == null) return;
   log.infof("shutdown DaoUp(name=%s)", name);
   try {
     Mirror.me(dataSource).invoke(dataSource, "close");
   } catch (Throwable e) {
   }
   this.dataSource = null;
   this.dao = null;
 }
Exemplo n.º 20
0
    public Class<?>[] extract(Mirror<?> mirror) {
      Class<?> theType = mirror.getType();
      List<Class<?>> re = new ArrayList<Class<?>>(5);

      // 原生类型,增加其外覆类
      if (theType.isPrimitive()) {
        re.add(mirror.getWrapperClass());
        // 数字
        if (theType != boolean.class && theType != char.class) {
          re.add(Number.class);
        }
      }
      // 日历
      else if (mirror.isOf(Calendar.class)) {
        re.add(Calendar.class);
      }
      // 其他类型,直接增加,并试图判断其抽象类
      else {
        re.add(theType);
        // 枚举
        if (mirror.klass.isEnum()) {
          re.add(Enum.class);
        }
        // 数组
        else if (mirror.klass.isArray()) {
          re.add(Array.class);
        }
        // 字符串
        else if (mirror.isStringLike()) re.add(CharSequence.class);
        // 数字
        else if (mirror.isNumber()) {
          re.add(Number.class);
        }
        // Map
        else if (mirror.isOf(Map.class)) {
          re.add(Map.class);
        }
        // 列表
        else if (mirror.isOf(List.class)) {
          re.add(List.class);
          re.add(Collection.class);
        }
        // 集合
        else if (mirror.isOf(Collection.class)) {
          re.add(Collection.class);
        }
      }
      // 最后确保 Object 一定被加上了
      if (theType != Object.class) re.add(Object.class);

      return re.toArray(new Class<?>[re.size()]);
    }
Exemplo n.º 21
0
  /**
   * 根据给定的一个方法,判断其是 Getter 还是 Setter
   *
   * <p>对于回调会接受三个参数
   *
   * <pre>
   * callback(虚字段名, getter, setter)
   * </pre>
   *
   * 回调都会给一个参数,表示这个方法对应的虚拟字段名。所谓"虚拟字段",就比如
   *
   * <ul>
   *   <li>如果是 setAbc : 那么就是 "abc"
   *   <li>如果是 getAbc : 那么就是 "abc"
   *   <li>如果是 isAbc : 那么就是 "abc"
   * </ul>
   *
   * 而 getter 或者 setter 参数如果为 null,则表示本函数未发现对应的 getter|setter
   *
   * @param method 方法对象
   * @param callback 回调, 如果为 null,则无视
   * @param whenError 如果本方法即不是 Getter 也不是 Setter 的回调, 如果为 null,则无视
   */
  public static void evalGetterSetter(
      Method method, Callback3<String, Method, Method> callback, Callback<Method> whenError) {
    String name = method.getName();
    Method getter = null;
    Method setter = null;

    // 是 getter
    if (name.startsWith("get") && method.getParameterTypes().length == 0) {
      name = Strings.lowerFirst(name.substring(4));
      getter = method;
      // 寻找 setter
      try {
        setter =
            method
                .getDeclaringClass()
                .getMethod("set" + Strings.capitalize(name), method.getReturnType());
      } catch (Exception e) {
      }

    }
    // 布尔的 getter
    else if (name.startsWith("is")
        && Mirror.me(method.getReturnType()).isBoolean()
        && method.getParameterTypes().length == 0) {
      name = Strings.lowerFirst(name.substring(3));
      getter = method;
      // 寻找 setter
      try {
        setter =
            method
                .getDeclaringClass()
                .getMethod("set" + Strings.capitalize(name), method.getReturnType());
      } catch (Exception e) {
      }
    }
    // 是 setter
    else if (name.startsWith("set") && method.getParameterTypes().length == 1) {
      name = Strings.lowerFirst(name.substring(4));
      setter = method;
      // 寻找 getter
      try {
        getter = method.getDeclaringClass().getMethod("get" + Strings.capitalize(name));
      } catch (Exception e) {
      }

    }
    // 虾米都不是,错!
    else {
      if (null != whenError) whenError.invoke(method);
      return;
    }
    // 最后调用回调
    if (null != callback) callback.invoke(name, getter, setter);
  }
Exemplo n.º 22
0
  public Object calculate() {
    // 如果直接调用计算方法,那基本上就是直接调用属性了吧...我也不知道^^
    Object obj = fetchVar();
    if (obj == null) {
      throw new ElException("obj is NULL, can't call obj." + right);
    }
    if (obj instanceof Map) {
      Map<?, ?> om = (Map<?, ?>) obj;
      if (om.containsKey(right.toString())) {
        return om.get(right.toString());
      }
    }
    if (obj instanceof Context) {
      Context sc = (Context) obj;
      if (sc.has(right.toString())) {
        return sc.get(right.toString());
      }
    }

    Mirror<?> me = Mirror.me(obj);
    return me.getValue(obj, right.toString());
  }
Exemplo n.º 23
0
 /**
  * 获取当前对象,所有的方法,包括私有方法。递归查找至自己某一个父类为止 。
  *
  * <p>并且这个按照名称,消除重复的方法。子类方法优先
  *
  * @param top 截至的父类
  * @return 方法数组
  */
 public Method[] getAllDeclaredMethods(Class<?> top) {
   Class<?> cc = klass;
   Map<String, Method> map = new LinkedHashMap<String, Method>();
   while (null != cc && cc != Object.class) {
     Method[] fs = cc.getDeclaredMethods();
     for (int i = 0; i < fs.length; i++) {
       String key = fs[i].getName() + Mirror.getParamDescriptor(fs[i].getParameterTypes());
       if (!map.containsKey(key)) map.put(key, fs[i]);
     }
     cc = cc.getSuperclass() == top ? null : cc.getSuperclass();
   }
   return map.values().toArray(new Method[map.size()]);
 }
Exemplo n.º 24
0
    @SuppressWarnings({"rawtypes", "unchecked"})
    public void init() {
      List<LinkField> lfs = new ArrayList<LinkField>();
      lfs.addAll(ones.getAll());
      lfs.addAll(manys.getAll());
      lfs.addAll(manymanys.getAll());
      if (lfs.isEmpty()) return;
      if (log.isDebugEnabled()) log.debug("Found links , enable lazy!! -->" + type);

      Mirror<T> mirror = Mirror.me(type);
      List<InterceptorPair> interceptorPairs = new ArrayList<InterceptorPair>();
      // 准备拦截器
      for (LinkField lf : lfs) {
        String fieldName = lf.getName();
        try {
          Method setter = mirror.getSetter(mirror.getField(fieldName));
          LazyMethodInterceptor lmi = new LazyMethodInterceptor(setter, fieldName);
          interceptorPairs.add(
              new InterceptorPair(
                  lmi,
                  MethodMatcherFactory.matcher(
                      "^(get|set)" + Strings.upperFirst(fieldName) + "$")));
        } catch (Throwable e) {
          if (log.isWarnEnabled()) log.warn("Not setter found for LazyLoading ?!", e);
        }
      }
      // 生成Aop化的类
      ClassAgent agent = new AsmClassAgent();
      for (InterceptorPair interceptorPair : interceptorPairs)
        agent.addInterceptor(
            interceptorPair.getMethodMatcher(), interceptorPair.getMethodInterceptor());
      Class lazyClass = agent.define(DefaultClassDefiner.defaultOne(), type);

      // 检查对象的创建方法
      BornContext<T> bc = Borns.evalByArgTypes(type, ResultSet.class);
      if (null == bc) this.bornByDefault = Mirror.me(lazyClass).getBorningByArgTypes();
      else this.bornByRS = bc.getBorning();
    }
Exemplo n.º 25
0
 public void destroy(NutConfig conf) {
   Markdowns.cache = null;
   // 非mysql数据库,或多webapp共享mysql驱动的话,以下语句删掉
   try {
     Mirror.me(Class.forName("com.mysql.jdbc.AbandonedConnectionCleanupThread"))
         .invoke(null, "shutdown");
   } catch (Throwable e) {
   }
   // 解决quartz有时候无法停止的问题
   try {
     conf.getIoc().get(Scheduler.class).shutdown(true);
   } catch (Exception e) {
   }
 }
Exemplo n.º 26
0
 /**
  * 获得一个对象的长度。它可以接受:
  *
  * <ul>
  *   <li>null : 0
  *   <li>数组
  *   <li>集合
  *   <li>Map
  *   <li>一般 Java 对象。 返回 1
  * </ul>
  *
  * 如果你想让你的 Java 对象返回不是 1 , 请在对象中声明 length() 函数
  *
  * @param obj
  * @return 对象长度
  */
 public static int length(Object obj) {
   if (null == obj) return 0;
   if (obj.getClass().isArray()) {
     return Array.getLength(obj);
   } else if (obj instanceof Collection<?>) {
     return ((Collection<?>) obj).size();
   } else if (obj instanceof Map<?, ?>) {
     return ((Map<?, ?>) obj).size();
   }
   try {
     return (Integer) Mirror.me(obj.getClass()).invoke(obj, "length");
   } catch (Exception e) {
   }
   return 1;
 }
Exemplo n.º 27
0
 /**
  * 修改 get 后的值,以便修改查询的 DBObject
  *
  * @param val get 后的值
  * @return 修改 get 后的值,这个值是 ejecting 从对象中取出的
  */
 public Object adaptForFormatQuery(Object val) {
   if (null == val) return null;
   //
   Mirror<?> vMirror = Mirror.me(val.getClass());
   // 如果值为 Map,且自己的类型不是 Map,那么就是深入修改 Map 的各个修改器的键 ...
   if (vMirror.isMap() && !field.getMirror().isMap()) {
     final Map<String, Object> map = new HashMap<String, Object>();
     Lang.each(
         val,
         true,
         new Each<Map.Entry<String, Object>>() {
           public void invoke(int index, Entry<String, Object> ele, int length) {
             String key = ele.getKey();
             if (null != key && key.startsWith("$")) {
               map.put(key, adaptForFormatQuery(ele.getValue()));
             }
           }
         });
     return map;
   }
   // 如果值为集合或者数组, 且自己不为集合或者数组,则生成个新数组返回
   else if (vMirror.isContainer() && !field.getMirror().isContainer()) {
     int len = Lang.length(val);
     final Object array = Array.newInstance(Object.class, len);
     Lang.each(
         val,
         false,
         new Each<Object>() {
           public void invoke(int index, Object o, int length) {
             Array.set(array, index, adaptForFormatQuery(o));
           }
         });
     return array;
   }
   return adaptForGet(val, false);
 }
Exemplo n.º 28
0
 /**
  * 根据名称获取一个 Getter。
  *
  * <p>比如,你想获取 abc 的 getter ,那么优先查找 getAbc(),如果没有则查找isAbc(),最后才是查找 abc()。
  *
  * @param fieldName
  * @return 方法
  * @throws NoSuchMethodException 没有找到 Getter
  */
 public Method getGetter(String fieldName) throws NoSuchMethodException {
   String fn = Strings.capitalize(fieldName);
   String _get = "get" + fn;
   String _is = "is" + fn;
   for (Method method : klass.getMethods()) {
     if (method.getParameterTypes().length != 0) continue;
     if (_get.equals(method.getName())) return method;
     if (_is.equals(method.getName())) {
       if (!Mirror.me(method.getReturnType()).isBoolean()) throw new NoSuchMethodException();
       return method;
     }
     if (fieldName.equals(method.getName())) return method;
   }
   throw Lang.makeThrow(
       NoSuchMethodException.class,
       "Fail to find getter for [%s]->[%s]",
       klass.getName(),
       fieldName);
 }
Exemplo n.º 29
0
 /**
  * @param klass 类型
  * @return 获得一个类型的描述符
  */
 public static String getTypeDescriptor(Class<?> klass) {
   if (klass.isPrimitive()) {
     if (klass == void.class) return "V";
     else if (klass == int.class) return "I";
     else if (klass == long.class) return "J";
     else if (klass == byte.class) return "B";
     else if (klass == short.class) return "S";
     else if (klass == float.class) return "F";
     else if (klass == double.class) return "D";
     else if (klass == char.class) return "C";
     else
       /* if(klass == boolean.class) */
       return "Z";
   }
   StringBuilder sb = new StringBuilder();
   if (klass.isArray()) {
     return sb.append('[').append(getTypeDescriptor(klass.getComponentType())).toString();
   }
   return sb.append('L').append(Mirror.getPath(klass)).append(';').toString();
 }
Exemplo n.º 30
0
 public Object run(List<Object> param) {
   Object obj = fetchVar();
   Mirror<?> me = null;
   if (obj == null) throw new NullPointerException();
   if (obj instanceof Class) {
     // 也许是个静态方法
     me = Mirror.me(obj);
     try {
       return me.invoke(obj, right.toString(), param.toArray());
     } catch (InvokingException e) {
       throw e;
     } catch (Throwable e) {
       if (Lang.unwrapThrow(e) instanceof NoSuchMethodException) {
         me = Mirror.me(obj.getClass().getClass());
         return me.invoke(obj, right.toString(), param.toArray());
       }
       throw Lang.wrapThrow(e);
     }
   } else {
     me = Mirror.me(obj);
     return me.invoke(obj, right.toString(), param.toArray());
   }
 }