コード例 #1
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();
    }