Example #1
0
 private Object findAncestor(Class<?> clazz) {
   // First check enclosing classes
   Class<?> c = clazz.getDeclaringClass();
   while (c != null) {
     if (c.isAnnotationPresent(Gwtc.class)) {
       return c;
     }
     c = c.getDeclaringClass();
   }
   Package p = clazz.getPackage();
   if (p.getAnnotation(Gwtc.class) != null) {
     return p;
   }
   Object o = findAncestor(p);
   if (o == null) {
     c = clazz.getSuperclass();
     while (c != null) {
       if (c.isAnnotationPresent(Gwtc.class)) {
         return c;
       }
       c = c.getSuperclass();
     }
   }
   return o;
 }
  @Test
  public void jaxbClassesTest() throws Exception {
    Assume.assumeTrue(TestType.JAXB.equals(getType()));

    Set<Class<?>> jaxbClasses = reflections.getTypesAnnotatedWith(XmlRootElement.class);

    assertTrue("Not enough classes found! [" + jaxbClasses.size() + "]", jaxbClasses.size() > 20);

    String className = null;
    try {
      for (Class<?> jaxbClass : jaxbClasses) {
        if (jaxbClass.getDeclaringClass() != null
            && jaxbClass.getDeclaringClass().getSimpleName().endsWith("Test")) {
          continue;
        }
        className = jaxbClass.getName();
        Constructor<?> construct = jaxbClass.getConstructor(new Class[] {});
        Object jaxbInst = construct.newInstance(new Object[] {});
        testRoundTrip(jaxbInst);
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail(className + ": " + e.getClass().getSimpleName() + " [" + e.getMessage() + "]");
    }
  }
 /** Is c1 an inner class of c2? */
 protected boolean isInnerClass(Class c1, final Class c2) {
   Class c = c1.getDeclaringClass();
   if (c == null) {
     try {
       final Field f = c1.getField("declaring$Class$Reference$0");
       c = (Class) f.get(null);
     } catch (final Exception e) {
     }
   }
   c1 = c;
   while (c != null) {
     if (c == c2) {
       return true;
     }
     c = c.getDeclaringClass();
     if (c == null) {
       try {
         final Field f = c1.getField("declaring$Class$Reference$0");
         c = (Class) f.get(null);
       } catch (final Exception e) {
       }
     }
     c1 = c;
   }
   return false;
 }
 public static <T> T newInnerInstance(Object instance, Class<T> innerClass) throws Exception {
   if (innerClass.getDeclaringClass() != null
       && (innerClass.getModifiers() & Modifier.STATIC) == 0) {
     Constructor<T> c =
         innerClass.getDeclaredConstructor(new Class[] {innerClass.getDeclaringClass()});
     return c.newInstance(new Object[] {instance});
   } else {
     return innerClass.newInstance();
   }
 }
Example #5
0
 public void addEnclosingClasses(Class<?> c) {
   c = c.getDeclaringClass();
   while (c != null) {
     Gwtc gwtc = c.getAnnotation(Gwtc.class);
     if (gwtc != null && addClass(c)) {
       addGwtcClass(gwtc, c);
     }
     c = c.getDeclaringClass();
   }
 }
 @Test
 public void testDeclaringType() throws Exception {
   for (Class<?> type : standardTypes) {
     assertThat(
         describe(type).getDeclaringType(),
         type.getDeclaringClass() == null
             ? nullValue(TypeDescription.class)
             : is((TypeDescription) new TypeDescription.ForLoadedType(type.getDeclaringClass())));
   }
 }
Example #7
0
 public static int getNesting(Class<?> clazz) {
   if (clazz.isMemberClass() && !isStatic(clazz)) {
     return 1 + getNesting(clazz.getDeclaringClass());
   } else {
     return 0;
   }
 }
Example #8
0
  public static String canonicalName(Class clazz) {
    StringBuilder name = new StringBuilder();

    if (clazz.isArray()) {
      name.append(canonicalName(clazz.getComponentType()));
      name.append("[]");
    } else if (clazz.getDeclaringClass() == null) {
      name.append(clazz.getName());
    } else {
      name.append(canonicalName(clazz.getDeclaringClass()));
      name.append(".");
      name.append(clazz.getName().substring(clazz.getDeclaringClass().getName().length() + 1));
    }

    return name.toString();
  }
  public static Class<?> resolveClassOf(final Class<? extends IElement> element)
      throws ClassNotFoundException {
    Class<?> cursor = element;
    List<Class<? extends IElement>> path = Lists.newArrayList();

    while (cursor != null && IElement.class.isAssignableFrom(cursor)) {
      //noinspection unchecked
      path.add((Class<? extends IElement>) cursor);
      cursor = cursor.getDeclaringClass();
    }

    Collections.reverse(path);

    int i = 1; // first one is the store type

    List<String> ognl = Lists.newArrayList();
    while (i < path.size()
        && (IPackage.class.isAssignableFrom(path.get(i))
            || IClass.class.isAssignableFrom(path.get(i)))) {
      ognl.add(path.get(i).getSimpleName());
      i++;
    }

    String classOgnl = Joiner.on(".").join(ognl).replace(".$", "$");
    return Class.forName(classOgnl);
  }
Example #10
0
  private void generateView(
      Map<String, DesignDocument.View> views, Method me, Class<?> handledType) {
    String name = me.getName();
    if (!name.startsWith("findBy") && !name.equals("getAll")) {
      throw new ViewGenerationException(
          String.format(
              "The method: %s in %s annotated with GenerateView does not conform to the naming convention of 'findByXxxx'",
              name, me.getDeclaringClass()));
    }

    Class<?> type = resolveReturnType(me);
    if (type == null) {
      if (handledType != null) {
        type = handledType;
      } else {
        throw new ViewGenerationException(
            "Could not resolve return type for method: %s in %s",
            me.getName(), me.getDeclaringClass());
      }
    }

    String typeDiscriminator = resolveTypeDiscriminator(type);

    if (name.equals("getAll")) {
      if (typeDiscriminator.length() < 1) {
        throw new ViewGenerationException(
            String.format(
                "Cannot generate 'all' view for %s. No type discriminator could be resolved. Try annotate unique field(s) with @TypeDiscriminator",
                type.getDeclaringClass()));
      }
      views.put("all", generateAllView(typeDiscriminator));
      return;
    }

    String finderName = name.substring(6);
    String fieldName = resolveFieldName(me, finderName);
    Method getter = findMethod(type, "get" + fieldName);
    if (getter == null) {
      // try pluralis
      fieldName += "s";
      getter = findMethod(type, "get" + fieldName);
    }
    if (getter == null) {
      throw new ViewGenerationException(
          "Could not generate view for method %s. No get method found for property %s in %s",
          name, name.substring(6), type);
    }

    fieldName = firstCharToLowerCase(fieldName);

    DesignDocument.View view;
    if (isIterable(getter.getReturnType())) {
      view = generateFindByIterableView(fieldName, typeDiscriminator);
    } else {
      view = generateFindByView(fieldName, typeDiscriminator);
    }

    views.put("by_" + firstCharToLowerCase(finderName), view);
  }
Example #11
0
 /** Create a name for the given class. The resulting name will be in a resolved state. */
 public MemberName(Class<?> type) {
   init(
       type.getDeclaringClass(),
       type.getSimpleName(),
       type,
       flagsMods(IS_TYPE, type.getModifiers()));
   vmindex = 0; // isResolved
   assert (isResolved());
 }
 ParameterizedTypeImpl(Class<?> rawType, Type[] actualTypeArguments, Type ownerType) {
   this.actualTypeArguments = actualTypeArguments;
   this.rawType = rawType;
   if (ownerType != null) {
     this.ownerType = ownerType;
   } else {
     this.ownerType = rawType.getDeclaringClass();
   }
   validateConstructorArguments();
 }
 @Override
 public <T extends Searchable> Future<Long> count(final Specification<T> specification) {
   final Class<?> specClass = specification.getClass();
   final String parentName = client.getDslName(specClass.getDeclaringClass());
   return client.sendRequest(
       Long.class,
       DOMAIN_URI + "count/" + parentName + "?specification=" + specClass.getSimpleName(),
       "PUT",
       specification,
       new int[] {200});
 }
Example #14
0
 @Override
 @SuppressWarnings("unchecked")
 public <T extends ICode> T getCode(final Class<T> type) {
   synchronized (m_codeTypeMapLock) {
     if (type == null) {
       return null;
     }
     Class declaringCodeTypeClass = null;
     if (type.getDeclaringClass() != null) {
       // code is inner type of code type or another code
       Class c = type.getDeclaringClass();
       while (c != null && !(ICodeType.class.isAssignableFrom(c))) {
         c = c.getDeclaringClass();
       }
       declaringCodeTypeClass = c;
     }
     if (declaringCodeTypeClass == null) {
       try {
         declaringCodeTypeClass = type.newInstance().getCodeType().getClass();
       } catch (Throwable t) {
         LOG.error("find code " + type, t);
       }
     }
     ICodeType codeType = getCodeType(declaringCodeTypeClass);
     final Holder<ICode> codeHolder = new Holder<ICode>(ICode.class);
     ICodeVisitor v =
         new ICodeVisitor() {
           @Override
           public boolean visit(ICode code, int treeLevel) {
             if (code.getClass() == type) {
               codeHolder.setValue(code);
               return false;
             }
             return true;
           }
         };
     codeType.visit(v);
     return (T) codeHolder.getValue();
   }
 }
Example #15
0
  public static void main(String[] args) throws Exception {
    Class<ClassTest> clazz = ClassTest.class;

    System.out.println("=============================================");
    Constructor[] ctors = clazz.getDeclaredConstructors();
    System.out.println("classTest的全部构造器如下:");
    for (Constructor c : ctors) {
      System.out.println(c);
    }

    System.out.println("=============================================");
    Constructor[] publicCtors = clazz.getConstructors();
    System.out.println("ClassTest的全部public构造器如下:");
    for (Constructor c : publicCtors) {
      System.out.println(c);
    }

    System.out.println("=============================================");
    Method[] mtds = clazz.getMethods();
    System.out.println("ClassTest的全部public方法如下:");
    for (Method md : mtds) {
      System.out.println(md);
    }

    System.out.println("=============================================");
    System.out.println("ClassTest带一个字符串参数的info方法为:" + clazz.getMethod("info", String.class));

    Annotation[] ans = clazz.getAnnotations();
    System.out.println("ClassTest的全部annotation为:");
    for (Annotation an : ans) {
      System.out.println(an);
    }
    System.out.println("该元素上的@SuppressWarnings注释为:" + clazz.getAnnotation(SuppressWarnings.class));

    System.out.println("=============================================");
    Class<?>[] inners = clazz.getDeclaredClasses();
    System.out.println("ClassTest的全部内部类如下:");
    for (Class c : inners) {
      System.out.println(c);
    }

    System.out.println("=============================================");

    Class inClazz = Class.forName("ClassTest$Inner");
    System.out.println("inClazz对应的外部类为:" + inClazz.getDeclaringClass());
    System.out.println("ClassTest的包为:" + clazz.getPackage());
    System.out.println("ClassTest的父类:" + clazz.getSuperclass());
  }
Example #16
0
 /**
  * Determines the class to use for naming a variable that contains the given value.
  *
  * <p>Will return the class of the given value, except when encountering a JDK proxy, in which
  * case it will determine the 'primary' interface implemented by that proxy.
  *
  * @param value the value to check
  * @return the class to use for naming a variable
  */
 private static Class<?> getClassForValue(Object value) {
   Class<?> valueClass = value.getClass();
   if (Proxy.isProxyClass(valueClass)) {
     Class<?>[] ifcs = valueClass.getInterfaces();
     for (Class<?> ifc : ifcs) {
       if (!ignoredInterfaces.contains(ifc)) {
         return ifc;
       }
     }
   } else if (valueClass.getName().lastIndexOf('$') != -1
       && valueClass.getDeclaringClass() == null) {
     // '$' in the class name but no inner class -
     // assuming it's a special subclass (e.g. by OpenJPA)
     valueClass = valueClass.getSuperclass();
   }
   return valueClass;
 }
 private static Throwable makeLanguageStackTrace(
     @NotNull Throwable currentThrowable, @NotNull PsiFile file) {
   Throwable langThrowable = new Throwable();
   FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(file);
   if (builder == null) return currentThrowable;
   Class builderClass = builder.getClass();
   Class declaringClass = builderClass.getDeclaringClass();
   String guessedFileName =
       (declaringClass == null ? builderClass.getSimpleName() : declaringClass.getSimpleName())
           + ".java";
   StackTraceElement ste =
       new StackTraceElement(builder.getClass().getName(), "createModel", guessedFileName, 1);
   StackTraceElement[] originalStackTrace = currentThrowable.getStackTrace();
   StackTraceElement[] modifiedStackTrace = new StackTraceElement[originalStackTrace.length + 1];
   System.arraycopy(originalStackTrace, 0, modifiedStackTrace, 1, originalStackTrace.length);
   modifiedStackTrace[0] = ste;
   langThrowable.setStackTrace(modifiedStackTrace);
   return langThrowable;
 }
Example #18
0
 public TypeReference(final Class<?> clazz, final List<TypeReference> arguments) {
   boolean _isPrimitive = clazz.isPrimitive();
   if (_isPrimitive) {
     String _name = clazz.getName();
     String _plus = ("Type is primitive: " + _name);
     throw new IllegalArgumentException(_plus);
   }
   boolean _isAnonymousClass = clazz.isAnonymousClass();
   if (_isAnonymousClass) {
     String _name_1 = clazz.getName();
     String _plus_1 = ("Class is anonymous: " + _name_1);
     throw new IllegalArgumentException(_plus_1);
   }
   boolean _isLocalClass = clazz.isLocalClass();
   if (_isLocalClass) {
     String _name_2 = clazz.getName();
     String _plus_2 = ("Class is local: " + _name_2);
     throw new IllegalArgumentException(_plus_2);
   }
   Package _package = clazz.getPackage();
   String _name_3 = _package.getName();
   this.packageName = _name_3;
   ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList();
   this.simpleNames = _newArrayList;
   List<TypeReference> _elvis = null;
   if (arguments != null) {
     _elvis = arguments;
   } else {
     List<TypeReference> _emptyList = Collections.<TypeReference>emptyList();
     _elvis = _emptyList;
   }
   this.typeArguments = _elvis;
   Class<?> c = clazz;
   do {
     {
       String _simpleName = c.getSimpleName();
       this.simpleNames.add(0, _simpleName);
       Class<?> _declaringClass = c.getDeclaringClass();
       c = _declaringClass;
     }
   } while ((c != null));
 }
  private void treatPatchClass(CtClass patchCtClass) throws ClassNotFoundException {
    Class<?> clazz = Class.forName(patchCtClass.getName(), true, classLoader);
    PatchClass patchClass = GwtReflectionUtils.getAnnotation(clazz, PatchClass.class);

    if (!Patcher.class.isAssignableFrom(clazz) || !hasDefaultConstructor(clazz)) {
      throw new RuntimeException(
          "The @"
              + PatchClass.class.getSimpleName()
              + " annotated class '"
              + clazz.getName()
              + "' must implements "
              + Patcher.class.getSimpleName()
              + " interface and provide an empty constructor");
    }

    Patcher patcher = (Patcher) GwtReflectionUtils.instantiateClass(clazz);

    for (Class<?> c : patchClass.value()) {
      String targetName =
          c.isMemberClass()
              ? c.getDeclaringClass().getCanonicalName() + "$" + c.getSimpleName()
              : c.getCanonicalName();
      if (patchers.get(targetName) != null) {
        logger.error("Two patches for same class " + targetName);
        throw new RuntimeException("Two patches for same class " + targetName);
      }
      patchers.put(targetName, patcher);
      logger.debug("Add patch for class " + targetName + " : " + clazz.getCanonicalName());
    }
    for (String s : patchClass.classes()) {
      if (patchers.get(s) != null) {
        logger.error("Two patches for same class " + s);
        throw new RuntimeException("Two patches for same class " + s);
      }
      patchers.put(s, patcher);
      logger.debug("Add patch for class " + s + " : " + clazz.getCanonicalName());
    }
  }
Example #20
0
 /** Create an instance based on a Class. */
 public TypeName(Class<?> cls) {
   int dim = 0;
   Class<?> inner = cls;
   while (inner.isArray()) {
     inner = cls.getComponentType();
     dim += 1;
   }
   dimensions = dim;
   Class<?> parent = cls;
   int nesting = 0;
   while (parent.isMemberClass()) {
     nesting++;
     parent = parent.getDeclaringClass();
   }
   nestingLevel = nesting;
   baseQualifiedName = adaptQualifiedName(cls.getCanonicalName());
   baseBinaryName = cls.getName();
   primitive = cls.isPrimitive();
   shortName = buildShortName();
   qualifiedName = buildQualifiedName();
   binaryName = buildBinaryName();
   varargs = false;
 }
  @Override
  public <T extends Searchable> Future<List<T>> search(
      final Specification<T> specification,
      final Integer limit,
      final Integer offset,
      final Iterable<Map.Entry<String, Boolean>> order) {

    if (specification == null) throw new IllegalArgumentException("Specification can't be null");
    final Class<?> specClass = specification.getClass();
    @SuppressWarnings("unchecked")
    final Class<T> manifest = (Class<T>) specClass.getDeclaringClass();
    final String parentName = client.getDslName(manifest);

    final String url =
        Utils.appendLimitOffsetOrder(
            parentName + "?specification=" + specClass.getSimpleName(),
            limit,
            offset,
            order,
            false);

    return client.sendCollectionRequest(
        manifest, DOMAIN_URI + "search/" + url, "PUT", specification, new int[] {200});
  }
  private void generateObjectModelProxy(
      Class<?> objectModelClass, String objectModelProxyClassName, ClassVisitor cv) {

    Class<?> ownerClass = objectModelClass.getDeclaringClass();
    HibernateObjectModelMetadata hibernateObjectModelMetadata =
        this.getMetadataFactory().getMetadata(ownerClass);

    String objectModelInternalName = objectModelClass.getName().replace('.', '/');
    String objectModelProxyInternalName = objectModelProxyClassName.replace('.', '/');
    cv.visit(
        Opcodes.V1_7,
        Opcodes.ACC_PUBLIC,
        objectModelProxyInternalName,
        null,
        "java/lang/Object",
        new String[] {
          objectModelInternalName,
          ASM.getInternalName(ObjectModel.class),
          ASM.getInternalName(ObjectModelAppender.class)
        });

    cv.visitField(
            Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL,
            OBJECT_MODEL_IMPL_FACTORY,
            ASM.getDescriptor(ObjectModelFactory.class),
            null,
            null)
        .visitEnd();

    cv.visitField(Opcodes.ACC_PRIVATE, HIBERNATE_PROXY_OWNER, HIBERNATE_PROXY_DESC, null, null)
        .visitEnd();

    XMethodVisitor mv;

    mv =
        ASM.visitMethod(
            cv,
            Opcodes.ACC_PUBLIC,
            "<init>",
            '(' + ASM.getDescriptor(ObjectModelFactory.class) + HIBERNATE_PROXY_DESC + ")V",
            null,
            null);
    mv.visitCode();
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);

    mv.visitLdcInsn(Type.getType(objectModelClass));
    mv.visitMethodInsn(
        Opcodes.INVOKESTATIC,
        ASM.getInternalName(ObjectModelFactoryFactory.class),
        "factoryOf",
        "(Ljava/lang/Class;)" + ASM.getDescriptor(ObjectModelFactory.class),
        false);
    mv.visitFieldInsn(
        Opcodes.PUTSTATIC,
        objectModelProxyInternalName,
        OBJECT_MODEL_IMPL_FACTORY,
        ASM.getDescriptor(ObjectModelFactory.class));

    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ALOAD, 2);
    mv.visitFieldInsn(
        Opcodes.PUTFIELD,
        objectModelProxyInternalName,
        HIBERNATE_PROXY_OWNER,
        HIBERNATE_PROXY_DESC);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();

    int gernatedMask = 0;
    for (Method method : objectModelClass.getMethods()) {
      gernatedMask |=
          this.generateProxyMethodForReferenceMode(
              cv,
              method,
              objectModelProxyInternalName,
              objectModelClass,
              hibernateObjectModelMetadata);
    }
    if (!ObjectModel.class.isAssignableFrom(objectModelClass)) {
      for (Method method : ObjectModel.class.getMethods()) {
        gernatedMask |=
            this.generateProxyMethodForReferenceMode(
                cv,
                method,
                objectModelProxyInternalName,
                objectModelClass,
                hibernateObjectModelMetadata);
      }
    }
    if (gernatedMask
        != (1 << 8)
            - (hibernateObjectModelMetadata.getDeclaredEntityIdProperty() == null ? 4 : 1)) {
      throw new AssertionError();
    }

    mv =
        ASM.visitMethod(
            cv,
            Opcodes.ACC_PROTECTED,
            "writeReplace",
            "()Ljava/lang/Object;",
            null,
            new String[] {ASM.getInternalName(ObjectStreamException.class)});
    mv.visitCode();
    mv.visitTypeInsn(
        Opcodes.NEW, ASM.getInternalName(HibernateObjectModelProxyWritingReplacment.class));
    mv.visitInsn(Opcodes.DUP);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(
        Opcodes.INVOKESPECIAL,
        ASM.getInternalName(HibernateObjectModelProxyWritingReplacment.class),
        "<init>",
        '(' + ASM.getDescriptor(ObjectModel.class) + ")V",
        false);
    mv.visitInsn(Opcodes.ARETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();

    this.generateAppendTo(cv, objectModelProxyClassName);
    this.generateToString(cv);

    cv.visitEnd();
  }
  private static MetaData buildMetaData(Class<? extends QObject> clazz) {
    MetaData metaData = new MetaData();

    List<Method> slots = new ArrayList<Method>();

    Hashtable<String, Method> propertyReaders = new Hashtable<String, Method>();
    Hashtable<String, Method> propertyWriters = new Hashtable<String, Method>();
    Hashtable<String, Object> propertyDesignables = new Hashtable<String, Object>();
    Hashtable<String, Method> propertyResetters = new Hashtable<String, Method>();
    Hashtable<String, Boolean> propertyUser = new Hashtable<String, Boolean>();

    // First we get all enums actually declared in the class
    Hashtable<String, Class<?>> enums = new Hashtable<String, Class<?>>();
    int enumConstantCount = queryEnums(clazz, enums);
    int enumCount = enums.size(); // Get the size before we add external enums

    Method declaredMethods[] = clazz.getDeclaredMethods();
    for (Method declaredMethod : declaredMethods) {

      if (!declaredMethod.isAnnotationPresent(QtBlockedSlot.class)
          && ((declaredMethod.getModifiers() & Modifier.STATIC) != Modifier.STATIC)) {

        // If we can't convert the type, we don't list it
        String methodParameters = methodParameters(declaredMethod);
        String returnType = declaredMethod.getReturnType().getName();
        if ((methodParameters.equals("")
                || !internalTypeNameOfParameters(declaredMethod, 1).equals(""))
            && (returnType.equals("")
                || returnType.equals("void")
                || !internalTypeNameOfClass(declaredMethod.getReturnType(), 0).equals(""))) {
          slots.add(declaredMethod);
        }
      }

      // Rules for readers:
      // 1. Zero arguments
      // 2. Return something other than void
      // 3. We can convert the type
      Container reader = Container.readerAnnotation(declaredMethod);
      {
        if (reader != null
            && reader.enabled()
            && isValidGetter(declaredMethod)
            && !internalTypeNameOfClass(declaredMethod.getReturnType(), 0).equals("")) {

          // If the return type of the property reader is not registered, then
          // we need to register the owner class in the meta object (in which case
          // it has to be a QObject)
          Class<?> returnType = declaredMethod.getReturnType();

          int count = putEnumTypeInHash(returnType, enums);
          if (count < 0) {
            System.err.println(
                "Problem in property '"
                    + reader.name()
                    + "' in '"
                    + clazz.getName()
                    + "': Only enum types 1. declared inside QObject subclasses or the "
                    + "Qt interface and 2. declared without the QtBlockedEnum annotation "
                    + "are supported for properties");
            continue;
          }

          propertyReaders.put(reader.name(), declaredMethod);
          propertyDesignables.put(reader.name(), isDesignable(declaredMethod, clazz));
          propertyUser.put(reader.name(), isUser(declaredMethod));
        }
      }

      // Rules for writers:
      // 1. Takes exactly one argument
      // 2. Return void
      // 3. We can convert the type
      Container writer = Container.writerAnnotation(declaredMethod);
      {
        if (writer != null && writer.enabled() && isValidSetter(declaredMethod)) {
          propertyWriters.put(writer.name(), declaredMethod);
        }
      }

      // Rules for resetters:
      // 1. No arguments
      // 2. Return void
      {
        Container resetter = Container.resetterAnnotation(declaredMethod);

        if (resetter != null
            && declaredMethod.getParameterTypes().length == 0
            && declaredMethod.getReturnType() == Void.TYPE) {
          propertyResetters.put(resetter.name(), declaredMethod);
        }
      }

      // Check naming convention by looking for setXxx patterns, but only if it hasn't already been
      // annotated as a writer
      String declaredMethodName = declaredMethod.getName();
      if (writer == null
          && reader
              == null // reader can't be a writer, cause the signature doesn't match, just an
                      // optimization
          && declaredMethodName.startsWith("set")
          && declaredMethodName.length() > 3
          && Character.isUpperCase(declaredMethodName.charAt(3))
          && isValidSetter(declaredMethod)) {

        Class<?> paramType = declaredMethod.getParameterTypes()[0];
        String propertyName =
            Character.toLowerCase(declaredMethodName.charAt(3)) + declaredMethodName.substring(4);

        if (!propertyReaders.containsKey(propertyName)) {
          // We need a reader as well, and the reader must not be annotated as disabled
          // The reader can be called 'xxx', 'getXxx', 'isXxx' or 'hasXxx'
          // (just booleans for the last two)
          Method readerMethod =
              notBogus(getMethod(clazz, propertyName, null), propertyName, paramType);
          if (readerMethod == null)
            readerMethod =
                notBogus(
                    getMethod(clazz, "get" + capitalizeFirst(propertyName), null),
                    propertyName,
                    paramType);
          if (readerMethod == null && isBoolean(paramType))
            readerMethod =
                notBogus(
                    getMethod(clazz, "is" + capitalizeFirst(propertyName), null),
                    propertyName,
                    paramType);
          if (readerMethod == null && isBoolean(paramType))
            readerMethod =
                notBogus(
                    getMethod(clazz, "has" + capitalizeFirst(propertyName), null),
                    propertyName,
                    paramType);

          if (readerMethod != null) { // yay
            reader = Container.readerAnnotation(readerMethod);
            if (reader == null) {
              propertyReaders.put(propertyName, readerMethod);
              propertyWriters.put(propertyName, declaredMethod);

              propertyDesignables.put(propertyName, isDesignable(readerMethod, clazz));
              propertyUser.put(propertyName, isUser(readerMethod));
            }
          }
        }
      }
    }

    Field declaredFields[] = clazz.getDeclaredFields();
    List<Field> signalFields = new ArrayList<Field>();
    List<QtJambiInternal.ResolvedSignal> resolvedSignals =
        new ArrayList<QtJambiInternal.ResolvedSignal>();
    for (Field declaredField : declaredFields) {
      if (QtJambiInternal.isSignal(declaredField.getType())) {
        // If we can't convert all the types we don't list the signal
        QtJambiInternal.ResolvedSignal resolvedSignal =
            QtJambiInternal.resolveSignal(declaredField, declaredField.getDeclaringClass());
        String signalParameters = signalParameters(resolvedSignal);
        if (signalParameters.length() == 0
            || internalTypeNameOfSignal(resolvedSignal.types, signalParameters, 1).length() != 0) {
          signalFields.add(declaredField);
          resolvedSignals.add(resolvedSignal);
        }
      }
    }
    metaData.signalsArray = signalFields.toArray(new Field[0]);

    {
      int functionCount = slots.size() + signalFields.size();
      int propertyCount = propertyReaders.keySet().size();
      int propertyNotifierCount = 0; // FIXME (see QTabWidget)
      int constructorCount = 0; // FIXME (see QObject)
      int metaObjectFlags = 0; // FIXME DynamicMetaObject

      // Until 4.7.x QtJambi used revision=1 however due to a change in the way
      //  4.7.x works some features of QtJambi stopped working.
      // revision 1         = MO_HEADER_LEN=10
      // revision 2 (4.5.x) = MO_HEADER_LEN=12 (added: constructorCount, constructorData)
      // revision 3         = MO_HEADER_LEN=13 (added: flags)
      // revision 4 (4.6.x) = MO_HEADER_LEN=14 (added: signalCount)
      // revision 5 (4.7.x) = MO_HEADER_LEN=14 (normalization)
      // revision 6 (4.8.x) = MO_HEADER_LEN=14 (added support for qt_static_metacall)
      // revision 7 (5.0.x) = MO_HEADER_LEN=14 (Qt5 to break backwards compatibility)
      // The format is compatible to share the same encoding code
      //  then we can change the revision to suit the Qt
      /// implementation we are working with.

      final int MO_HEADER_LEN = 14; // header size
      final int CLASSINFO_LEN = 2; // class info size
      int len = MO_HEADER_LEN + CLASSINFO_LEN;
      len += functionCount * 5;
      len += propertyCount * 3;
      len += propertyNotifierCount;
      len += enumCount * 4;
      len += enumConstantCount * 2;
      len += constructorCount * 5;
      metaData.metaData = new int[len + 1]; // add EOD <NUL>

      int intDataOffset = 0; // the offsets used by this descriptor are based on ints (32bit values)

      // Add static header
      metaData.metaData[0] = resolveMetaDataRevision(); // Revision
      // metaData[1] = 0 // class name  (ints default to offset 0 into strings)
      intDataOffset += MO_HEADER_LEN;

      metaData.metaData[2] = 1; // class info count
      metaData.metaData[3] = intDataOffset; // class info offset
      intDataOffset += CLASSINFO_LEN;

      // Functions always start right after this header at offset MO_HEADER_LEN + CLASSINFO_LEN
      metaData.metaData[4] = functionCount;
      metaData.metaData[5] = functionCount == 0 ? 0 : intDataOffset;
      intDataOffset += functionCount * 5; // Each function takes 5 ints

      metaData.metaData[6] = propertyCount;
      metaData.metaData[7] = propertyCount == 0 ? 0 : intDataOffset;
      intDataOffset +=
          (propertyCount * 3)
              + propertyNotifierCount; // Each property takes 3 ints and each propertNotifier 1 int

      // Enums
      metaData.metaData[8] = enumCount;
      metaData.metaData[9] = enumCount == 0 ? 0 : intDataOffset;
      intDataOffset +=
          (enumCount * 4)
              + (enumConstantCount * 2); // Each enum takes 4 ints and each enumConst takes 2 ints
      // revision 1 ends here

      metaData.metaData[10] = constructorCount;
      metaData.metaData[11] = constructorCount == 0 ? 0 : intDataOffset;
      intDataOffset += constructorCount * 5;
      // revision 2 ends here
      metaData.metaData[12] = metaObjectFlags; // flags
      // revision 3 ends here
      metaData.metaData[13] = signalFields.size(); // signalCount
      // revision 4, 5 and 6 ends here

      int offset = 0;
      int metaDataOffset = MO_HEADER_LEN; // Header is currently 14 ints long
      Hashtable<String, Integer> strings = new Hashtable<String, Integer>();
      List<String> stringsInOrder = new ArrayList<String>();
      // Class name
      {
        String className = clazz.getName().replace(".", "::");
        stringsInOrder.add(className);
        strings.put(className, offset);
        offset += className.length() + 1;
      }

      // Class info
      {
        offset +=
            addString(
                metaData.metaData,
                strings,
                stringsInOrder,
                "__qt__binding_shell_language",
                offset,
                metaDataOffset++);
        offset +=
            addString(
                metaData.metaData, strings, stringsInOrder, "Qt Jambi", offset, metaDataOffset++);
      }

      metaData.originalSignatures = new String[signalFields.size() + slots.size()];

      // Signals (### make sure enum types are covered)
      for (int i = 0; i < signalFields.size(); ++i) {
        Field signalField = signalFields.get(i);
        QtJambiInternal.ResolvedSignal resolvedSignal = resolvedSignals.get(i);

        String javaSignalParameters = signalParameters(resolvedSignal);
        metaData.originalSignatures[i] =
            resolvedSignal.name
                + (javaSignalParameters.length() > 0 ? '<' + javaSignalParameters + '>' : "");

        String signalParameters =
            internalTypeNameOfSignal(resolvedSignal.types, javaSignalParameters, 1);

        // Signal name
        offset +=
            addString(
                metaData.metaData,
                strings,
                stringsInOrder,
                resolvedSignal.name + "(" + signalParameters + ")",
                offset,
                metaDataOffset++);

        // Signal parameters
        offset +=
            addString(
                metaData.metaData,
                strings,
                stringsInOrder,
                signalParameters,
                offset,
                metaDataOffset++);

        // Signal type (signals are always void in Qt Jambi)
        offset +=
            addString(metaData.metaData, strings, stringsInOrder, "", offset, metaDataOffset++);

        // Signal tag (Currently not supported by the moc either)
        offset +=
            addString(metaData.metaData, strings, stringsInOrder, "", offset, metaDataOffset++);

        // Signal flags
        int flags = MethodSignal;
        int modifiers = signalField.getModifiers();
        if ((modifiers & Modifier.PRIVATE) == Modifier.PRIVATE) flags |= MethodAccessPrivate;
        else if ((modifiers & Modifier.PROTECTED) == Modifier.PROTECTED)
          flags |= MethodAccessProtected;
        else if ((modifiers & Modifier.PUBLIC) == Modifier.PUBLIC) flags |= MethodAccessPublic;
        metaData.metaData[metaDataOffset++] = flags;
      }

      // Slots (### make sure enum types are covered, ### also test QFlags)
      for (int i = 0; i < slots.size(); ++i) {
        Method slot = slots.get(i);

        String javaMethodSignature = methodSignature(slot);
        metaData.originalSignatures[signalFields.size() + i] = javaMethodSignature;

        // Slot signature
        offset +=
            addString(
                metaData.metaData,
                strings,
                stringsInOrder,
                internalTypeNameOfMethodSignature(slot, 1),
                offset,
                metaDataOffset++);

        // Slot parameters
        offset +=
            addString(
                metaData.metaData,
                strings,
                stringsInOrder,
                internalTypeNameOfParameters(slot, 1),
                offset,
                metaDataOffset++);

        // Slot type
        String returnType = slot.getReturnType().getName();
        if (returnType.equals("void")) returnType = "";
        offset +=
            addString(
                metaData.metaData,
                strings,
                stringsInOrder,
                internalTypeNameOfClass(slot.getReturnType(), 0),
                offset,
                metaDataOffset++);

        // Slot tag (Currently not supported by the moc either)
        offset +=
            addString(metaData.metaData, strings, stringsInOrder, "", offset, metaDataOffset++);

        // Slot flags
        int flags = MethodSlot;
        int modifiers = slot.getModifiers();
        if ((modifiers & Modifier.PRIVATE) == Modifier.PRIVATE) flags |= MethodAccessPrivate;
        else if ((modifiers & Modifier.PROTECTED) == Modifier.PROTECTED)
          flags |= MethodAccessProtected;
        else if ((modifiers & Modifier.PUBLIC) == Modifier.PUBLIC) flags |= MethodAccessPublic;

        metaData.metaData[metaDataOffset++] = flags;
      }
      metaData.slotsArray = slots.toArray(new Method[0]);

      String propertyNames[] = propertyReaders.keySet().toArray(new String[0]);
      metaData.propertyReadersArray = new Method[propertyNames.length];
      metaData.propertyResettersArray = new Method[propertyNames.length];
      metaData.propertyWritersArray = new Method[propertyNames.length];
      metaData.propertyDesignablesArray = new Method[propertyNames.length];
      for (int i = 0; i < propertyNames.length; ++i) {
        Method reader = propertyReaders.get(propertyNames[i]);
        Method writer = propertyWriters.get(propertyNames[i]);
        Method resetter = propertyResetters.get(propertyNames[i]);
        Object designableVariant = propertyDesignables.get(propertyNames[i]);
        boolean isUser = propertyUser.get(propertyNames[i]);

        if (writer != null
            && !reader.getReturnType().isAssignableFrom(writer.getParameterTypes()[0])) {
          System.err.println(
              "QtJambiInternal.buildMetaData: Writer for property "
                  + propertyNames[i]
                  + " takes a type which is incompatible with reader's return type.");
          writer = null;
        }

        // Name
        offset +=
            addString(
                metaData.metaData,
                strings,
                stringsInOrder,
                propertyNames[i],
                offset,
                metaDataOffset++);

        // Type (need to special case flags and enums)
        Class<?> t = reader.getReturnType();
        boolean isEnumOrFlags = Enum.class.isAssignableFrom(t) || QFlags.class.isAssignableFrom(t);

        String typeName = null;
        if (isEnumOrFlags
            && t.getDeclaringClass() != null
            && QObject.class.isAssignableFrom(t.getDeclaringClass())) {
          // To avoid using JObjectWrapper for enums and flags (which is required in certain cases.)
          typeName = t.getDeclaringClass().getName().replace(".", "::") + "::" + t.getSimpleName();
        } else {
          typeName = internalTypeNameOfClass(t, 0);
        }
        offset +=
            addString(
                metaData.metaData, strings, stringsInOrder, typeName, offset, metaDataOffset++);

        int designableFlags = 0;
        if (designableVariant instanceof Boolean) {
          if ((Boolean) designableVariant) designableFlags = PropertyDesignable;
        } else if (designableVariant instanceof Method) {
          designableFlags = PropertyResolveDesignable;
          metaData.propertyDesignablesArray[i] = (Method) designableVariant;
        }

        // Flags
        metaData.metaData[metaDataOffset++] =
            PropertyReadable
                | PropertyStored
                | designableFlags
                | (writer != null ? PropertyWritable : 0)
                | (resetter != null ? PropertyResettable : 0)
                | (isEnumOrFlags ? PropertyEnumOrFlag : 0)
                | (isUser ? PropertyUser : 0);

        metaData.propertyReadersArray[i] = reader;
        metaData.propertyWritersArray[i] = writer;
        metaData.propertyResettersArray[i] = resetter;
      }

      // Each property notifier takes 1 int // FIXME

      // Enum types
      int enumConstantOffset = metaDataOffset + enumCount * 4;

      Hashtable<String, Class<?>> enclosingClasses = new Hashtable<String, Class<?>>();
      Collection<Class<?>> classes = enums.values();
      for (Class<?> cls : classes) {
        Class<?> enclosingClass = cls.getEnclosingClass();
        if (enclosingClass.equals(clazz)) {
          // Name
          offset +=
              addString(
                  metaData.metaData,
                  strings,
                  stringsInOrder,
                  cls.getSimpleName(),
                  offset,
                  metaDataOffset++);

          // Flags (1 == flags, 0 == no flags)
          metaData.metaData[metaDataOffset++] = QFlags.class.isAssignableFrom(cls) ? 0x1 : 0x0;

          // Get the enum class
          Class<?> enumClass = Enum.class.isAssignableFrom(cls) ? cls : null;
          if (enumClass == null) {
            enumClass = getEnumForQFlags(cls);
          }

          enumConstantCount = enumClass.getEnumConstants().length;

          // Count
          metaData.metaData[metaDataOffset++] = enumConstantCount;

          // Data
          metaData.metaData[metaDataOffset++] = enumConstantOffset;

          enumConstantOffset += 2 * enumConstantCount;
        } else if (!enclosingClass.isAssignableFrom(clazz)
            && !enclosingClasses.contains(enclosingClass.getName())) {
          // If the enclosing class of an enum is not in the current class hierarchy, then
          // the generated meta object needs to have a pointer to its meta object in the
          // extra-data.
          enclosingClasses.put(enclosingClass.getName(), enclosingClass);
        }
      }
      metaData.extraDataArray = enclosingClasses.values().toArray(new Class<?>[0]);

      // Enum constants
      for (Class<?> cls : classes) {

        if (cls.getEnclosingClass().equals(clazz)) {
          // Get the enum class
          Class<?> enumClass = Enum.class.isAssignableFrom(cls) ? cls : null;
          if (enumClass == null) {
            enumClass = getEnumForQFlags(cls);
          }

          Enum<?> enumConstants[] = (Enum[]) enumClass.getEnumConstants();

          for (Enum<?> enumConstant : enumConstants) {
            // Key
            offset +=
                addString(
                    metaData.metaData,
                    strings,
                    stringsInOrder,
                    enumConstant.name(),
                    offset,
                    metaDataOffset++);

            // Value
            metaData.metaData[metaDataOffset++] =
                enumConstant instanceof QtEnumerator
                    ? ((QtEnumerator) enumConstant).value()
                    : enumConstant.ordinal();
          }
        }
      }

      // EOD
      metaData.metaData[metaDataOffset++] = 0;

      int stringDataOffset = 0;
      metaData.stringData = new byte[offset + 1];

      for (String s : stringsInOrder) {
        assert stringDataOffset == strings.get(s);
        System.arraycopy(s.getBytes(), 0, metaData.stringData, stringDataOffset, s.length());
        stringDataOffset += s.length();
        metaData.stringData[stringDataOffset++] = 0;
      }
    }

    return metaData;
  }
Example #24
0
 public JClass outer() {
   Class p = _class.getDeclaringClass();
   if (p == null) return null;
   return ref(p);
 }
Example #25
0
  /**
   * Search there is a field descriptor which can accept one of the class descriptor which match the
   * given name and namespace.
   *
   * @param name XML name of the field
   * @param namespace namespace of the field
   * @param classDesc the class descriptor to match against
   * @param cdResolver the class descriptor resolver to use
   * @return An array of InheritanceMatch.
   * @throws MarshalException if the resolver called fails fatally
   */
  protected InheritanceMatch[] searchInheritance(
      final String name, final String namespace, final XMLClassDescriptor classDesc)
      throws MarshalException {
    Iterator classDescriptorIterator = null;

    try {
      // -- A little required logic for finding Not-Yet-Loaded
      // -- descriptors
      String className = getJavaNaming().toJavaClassName(name);
      // -- should use namespace-to-prefix mappings, but
      // -- just create package for now.
      Class clazz = classDesc.getJavaClass();
      String pkg = null;
      if (clazz != null) {
        while (clazz.getDeclaringClass() != null) {
          clazz = clazz.getDeclaringClass();
        }
        pkg = clazz.getName();
        int idx = pkg.lastIndexOf('.');
        if (idx >= 0) {
          pkg = pkg.substring(0, idx + 1);
          className = pkg + className;
        }
      }
      getInternalContext()
          .getXMLClassDescriptorResolver()
          .resolve(className, classDesc.getClass().getClassLoader());
      // -- end Not-Yet-Loaded descriptor logic

      // -- resolve all by XML name + namespace URI
      classDescriptorIterator =
          getInternalContext()
              .getXMLClassDescriptorResolver()
              .resolveAllByXMLName(name, namespace, null);
    } catch (ResolverException rx) {
      Throwable actual = rx.getCause();
      if (actual instanceof MarshalException) {
        throw (MarshalException) actual;
      }
      if (actual != null) {
        throw new MarshalException(actual);
      }
      throw new MarshalException(rx);
    }

    Vector inheritanceList = null;
    XMLFieldDescriptor descriptor = null;
    XMLFieldDescriptor[] descriptors = classDesc.getElementDescriptors();
    XMLClassDescriptor cdInherited = null;

    if (classDescriptorIterator.hasNext()) {
      while (classDescriptorIterator.hasNext() && (descriptor == null)) {
        cdInherited = (XMLClassDescriptor) classDescriptorIterator.next();
        Class subclass = cdInherited.getJavaClass();

        for (int i = 0; i < descriptors.length; i++) {

          if (descriptors[i] == null) {
            continue;
          }

          // -- skip descriptors with special internal name
          if (INTERNAL_XML_NAME.equals(descriptors[i].getXMLName())) {
            continue;
          }

          // -- check for inheritence
          Class superclass = descriptors[i].getFieldType();

          // It is possible that the superclass is of type object if we use any node.
          if (superclass.isAssignableFrom(subclass) && (superclass != Object.class)) {
            descriptor = descriptors[i];
            if (inheritanceList == null) {
              inheritanceList = new Vector(3);
            }
            inheritanceList.addElement(new InheritanceMatch(descriptor, cdInherited));
          }
        }
      }
      // -- reset inherited class descriptor, if necessary
      if (descriptor == null) {
        cdInherited = null;
      }
    }

    if (inheritanceList != null) {
      InheritanceMatch[] result = new InheritanceMatch[inheritanceList.size()];
      inheritanceList.toArray(result);
      return result;
    }
    return NO_MATCH_ARRAY;
  }
 private static void test(Class<?> c) throws Exception {
   /* Every public nested class represents a test.  In each case, either
    * the class contains further nested classes, in which case we
    * call this method recursively; or it declares or inherits a
    * method called getThing() and it declares a static field
    * called "expect" which
    * is the Type of that method's return value.  The test consists
    * of checking that the value returned by
    * TypeResolver.resolveInClass is indeed this Type.
    */
   System.out.println("Test " + c);
   Class<?>[] nested = c.getClasses();
   Arrays.sort(nested, classNameComparator);
   for (Class<?> n : nested) test(n);
   final Method m;
   try {
     m = c.getMethod("getThing");
   } catch (NoSuchMethodException e) {
     if (nested.length == 0) {
       System.out.println(
           "TEST ERROR: class "
               + c.getName()
               + " has neither "
               + "nested classes nor getThing() method");
       failedCases.add(c);
     }
     return;
   }
   Object expect = null;
   try {
     Field f = c.getDeclaredField("expect");
     expect = f.get(null);
   } catch (NoSuchFieldException e) {
     Class<?> outer = c.getDeclaringClass();
     if (outer != null) {
       try {
         Field f = outer.getDeclaredField("expect" + c.getSimpleName());
         expect = f.get(null);
       } catch (NoSuchFieldException e1) {
       }
     }
   }
   if (expect == null) {
     System.out.println(
         "TEST ERROR: class " + c.getName() + " has getThing() method " + "but not expect field");
     failedCases.add(c);
     return;
   }
   Type t = m.getGenericReturnType();
   //        t = FixType.fixType(t, c);
   t = TypeResolver.resolveInClass(c, t);
   System.out.print("..." + t);
   // check expected value, and incidentally equals method defined
   // by private implementations of the various Type interfaces
   if (expect.equals(t) && t.equals(expect)) System.out.println(", as expected");
   else if ((expect.equals(t) || t.equals(expect)) && expect.toString().equals(t.toString()))
     System.out.println(", as workaround of the 8023301 bug");
   else {
     System.out.println(" BUT SHOULD BE " + expect);
     failedCases.add(c);
   }
 }
Example #27
0
  protected void _resolveBindings(Type t) {
    if (t == null) return;

    Class<?> raw;
    if (t instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) t;
      Type[] args = pt.getActualTypeArguments();
      if (args != null && args.length > 0) {
        Class<?> rawType = (Class<?>) pt.getRawType();
        TypeVariable<?>[] vars = rawType.getTypeParameters();
        if (vars.length != args.length) {
          throw new IllegalArgumentException(
              "Strange parametrized type (in class "
                  + rawType.getName()
                  + "): number of type arguments != number of type parameters ("
                  + args.length
                  + " vs "
                  + vars.length
                  + ")");
        }
        for (int i = 0, len = args.length; i < len; ++i) {
          TypeVariable<?> var = vars[i];
          String name = var.getName();
          if (_bindings == null) {
            _bindings = new LinkedHashMap<String, JavaType>();
          } else {
            /* 24-Mar-2010, tatu: Better ensure that we do not overwrite something
             *  collected earlier (since we descend towards super-classes):
             */
            if (_bindings.containsKey(name)) continue;
          }
          // first: add a placeholder to prevent infinite loops
          _addPlaceholder(name);
          // then resolve type
          _bindings.put(name, _typeFactory._constructType(args[i], this));
        }
      }
      raw = (Class<?>) pt.getRawType();
    } else if (t instanceof Class<?>) {
      raw = (Class<?>) t;
      /* [JACKSON-677]: If this is an inner class then the generics are defined on the
       * enclosing class so we have to check there as well.  We don't
       * need to call getEnclosingClass since anonymous classes declare
       * generics
       */
      _resolveBindings(raw.getDeclaringClass());
      /* 24-Mar-2010, tatu: Can not have true generics definitions, but can
       *   have lower bounds ("<T extends BeanBase>") in declaration itself
       */
      TypeVariable<?>[] vars = raw.getTypeParameters();
      if (vars != null && vars.length > 0) {
        JavaType[] typeParams = null;

        if (_contextType != null && raw.isAssignableFrom(_contextType.getRawClass())) {
          typeParams = _typeFactory.findTypeParameters(_contextType, raw);
        }

        for (int i = 0; i < vars.length; i++) {
          TypeVariable<?> var = vars[i];

          String name = var.getName();
          Type varType = var.getBounds()[0];
          if (varType != null) {
            if (_bindings == null) {
              _bindings = new LinkedHashMap<String, JavaType>();
            } else { // and no overwriting...
              if (_bindings.containsKey(name)) continue;
            }
            _addPlaceholder(name); // to prevent infinite loops

            if (typeParams != null) {
              _bindings.put(name, typeParams[i]);
            } else {
              _bindings.put(name, _typeFactory._constructType(varType, this));
            }
          }
        }
      }
    } else { // probably can't be any of these... so let's skip for now
      // if (type instanceof GenericArrayType) {
      // if (type instanceof TypeVariable<?>) {
      // if (type instanceof WildcardType) {
      return;
    }
    // but even if it's not a parameterized type, its super types may be:
    _resolveBindings(raw.getGenericSuperclass());
    for (Type intType : raw.getGenericInterfaces()) {
      _resolveBindings(intType);
    }
  }
Example #28
0
 /**
  * Finds the next parent element annotated with @Gwtc. <br>
  * This method should NOT be used to recurse parent hierarchy; instead use {@link #getParents()}
  *
  * @return the next parent with @Gwtc, if there is one.
  */
 public Object getParent() {
   if (!isFindParent()) {
     return null;
   }
   final boolean findAll = isFindAllParents();
   Object o = source;
   Class<?> c;
   switch (type) {
     case Method:
       if (!isFindEnclosingClasses()) {
         return null;
       }
       o = c = ((Method) o).getDeclaringClass();
       if (c.isAnnotationPresent(Gwtc.class)) {
         return c;
       } else if (!findAll) {
         return null;
       }
       // fallthrough
     case Class:
       c = (Class<?>) o;
       if (isFindEnclosingClasses()) {
         Class<?> search = c;
         while (!isObjectOrNull(search.getDeclaringClass())) {
           search = search.getDeclaringClass();
           if (search.isAnnotationPresent(Gwtc.class)) {
             return search;
           }
           if (!findAll) {
             break;
           }
         }
       }
       if (isFindSuperClasses()) {
         Class<?> search = c;
         while (!isObjectOrNull(search.getSuperclass())) {
           search = search.getSuperclass();
           if (search.isAnnotationPresent(Gwtc.class)) {
             return search;
           }
           if (!findAll) {
             break;
           }
         }
       }
       o = c.getPackage();
       // fallthrough
     case Package:
       Package p = (Package) o;
       String pkg = p.getName();
       if ("".equals(pkg)) {
         return null;
       }
       do {
         pkg = X_String.chopOrReturnEmpty(pkg, ".");
         p = GwtReflect.getPackage(pkg);
         if (p != null) {
           if (p.isAnnotationPresent(Gwtc.class)) {
             return p;
           }
           if (!findAll) {
             return null;
           }
         }
       } while (pkg.length() > 0);
   }
   return null;
 }