Ejemplo n.º 1
0
 protected final boolean isInt(final JakExpression expr) {
   Type type = expr.type(this.context);
   return type.equals(boolean.class)
       || type.equals(byte.class)
       || type.equals(char.class)
       || type.equals(short.class)
       || type.equals(int.class);
 }
Ejemplo n.º 2
0
  /**
   * Checks if two types are the same or are equivalent under a variable mapping given in the type
   * map that was provided.
   */
  private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {
    if (to.equals(from)) return true;

    if (from instanceof TypeVariable) {
      return to.equals(typeMap.get(((TypeVariable<?>) from).getName()));
    }

    return false;
  }
Ejemplo n.º 3
0
 @Test
 public void testgeneric5() throws SecurityException, NoSuchMethodException {
   System.out.println("====  testgeneric5 ====");
   Type map1 = GenericUtils.newMapType(String.class, String.class);
   Type map2 = GenericUtils.newMapType(String.class, Object.class);
   Type map3 = Map.class;
   Type c = GenericUtils.newGenericType(GenericTypeTemplateTest.class, java.sql.Date.class);
   ClassEx cw = new ClassEx(c);
   MethodEx method = cw.getFirstMethodByName("test4");
   System.out.println(map1.equals(method.getGenericParameterTypes()[0]));
   System.out.println(map2.equals(method.getGenericReturnType()));
 }
 /*
  * Don't consider parameter types that are available after conversion.
  * Message, Message<?> and Channel.
  */
 private boolean isEligibleParameter(MethodParameter methodParameter) {
   Type parameterType = methodParameter.getGenericParameterType();
   if (parameterType.equals(Channel.class)
       || parameterType.equals(org.springframework.amqp.core.Message.class)) {
     return false;
   }
   if (parameterType instanceof ParameterizedType) {
     ParameterizedType parameterizedType = (ParameterizedType) parameterType;
     if (parameterizedType.getRawType().equals(Message.class)) {
       return !(parameterizedType.getActualTypeArguments()[0] instanceof WildcardType);
     }
   }
   return !parameterType.equals(Message.class); // could be Message without a generic type
 }
Ejemplo n.º 5
0
  /**
   * Deserialize response body to Java object, according to the return type and the Content-Type
   * response header.
   *
   * @param <T> Type
   * @param response HTTP response
   * @param returnType The type of the Java object
   * @return The deserialized Java object
   * @throws ApiException If fail to deserialize response body, i.e. cannot read response body or
   *     the Content-Type of the response is not supported.
   */
  @SuppressWarnings("unchecked")
  public <T> T deserialize(Response response, Type returnType) throws ApiException {
    if (response == null || returnType == null) {
      return null;
    }

    if ("byte[]".equals(returnType.toString())) {
      // Handle binary response (byte array).
      try {
        return (T) response.body().bytes();
      } catch (IOException e) {
        throw new ApiException(e);
      }
    } else if (returnType.equals(File.class)) {
      // Handle file downloading.
      return (T) downloadFileFromResponse(response);
    }

    String respBody;
    try {
      if (response.body() != null) respBody = response.body().string();
      else respBody = null;
    } catch (IOException e) {
      throw new ApiException(e);
    }

    if (respBody == null || "".equals(respBody)) {
      return null;
    }

    String contentType = response.headers().get("Content-Type");
    if (contentType == null) {
      // ensuring a default content type
      contentType = "application/json";
    }
    if (isJsonMime(contentType)) {
      return json.deserialize(respBody, returnType);
    } else if (returnType.equals(String.class)) {
      // Expecting string, return the raw response body.
      return (T) respBody;
    } else {
      throw new ApiException(
          "Content type \"" + contentType + "\" is not supported for type: " + returnType,
          response.code(),
          response.headers().toMultimap(),
          respBody);
    }
  }
Ejemplo n.º 6
0
 /**
  * Get all elements in scope of type
  *
  * @param type Class we are looking for
  * @return List of VariableReferences
  */
 public List<VariableReference> getElements(Type type) {
   List<VariableReference> refs = new ArrayList<VariableReference>();
   for (Entry<VariableReference, Object> entry : pool.entrySet()) {
     if (type.equals(entry.getKey().getType())
         || (entry.getValue() != null && type.equals(entry.getValue().getClass()))) {
       refs.add(entry.getKey());
     }
   }
   /*
    * for(VariableReference ref : pool.keySet()) {
    *
    * // TODO: Exact match because it is used for comparison only at the
    * moment if(ref.getType().equals(type)) refs.add(ref); }
    */
   return refs;
 }
Ejemplo n.º 7
0
 @Override
 public Injectable<?> getInjectable(ComponentContext ctx, RequestUser ruAnnotation, Type type) {
   if (type.equals(String.class)) {
     return this;
   }
   return null;
 }
Ejemplo n.º 8
0
 private static int checkParameterizedType(
     String subroutineName,
     ParameterizedType expectedType,
     ArgumentsList arguments,
     List<LispObject> args,
     int argsCounter,
     int i) {
   Type rawType = expectedType.getRawType();
   Type expectedTypeArguments = expectedType.getActualTypeArguments()[0];
   try {
     if (((Class) rawType).isInstance(args.get(argsCounter))) {
       Type actualTypeArguments =
           ((ParameterizedType) (Type) args.get(argsCounter).getClass())
               .getActualTypeArguments()[0];
       if (!expectedTypeArguments.equals(actualTypeArguments)) {
         throw new WrongTypeArgumentException(
             ((Class) rawType).getSimpleName()
                 + "<"
                 + ((Class) expectedTypeArguments).getSimpleName()
                 + ">",
             args.get(argsCounter));
       }
       arguments.setValue(i, args.get(argsCounter));
       return argsCounter + 1;
     } else {
       if (arguments.isOptional(i)) return -1;
       throw new WrongTypeArgumentException(expectedType.toString(), args.get(argsCounter));
     }
   } catch (IndexOutOfBoundsException e) {
     if (arguments.isOptional(i)) return -1;
     throw new WrongNumberOfArgumentsException(subroutineName, i);
   }
 }
Ejemplo n.º 9
0
  @Test
  public void testgeneric4() throws SecurityException, NoSuchMethodException {
    System.out.println("====  testgeneric4 ====");

    Type type = GenericUtils.newArrayType(String.class);
    System.out.println(type.getClass().getName());
    System.out.println("isRawArray:" + GenericUtils.isRawArray(type));
    System.out.println("rawType:" + GenericUtils.getRawClass(type));

    Class<?> c = new String[0].getClass();
    System.out.println(c.getClass().getName());
    System.out.println(c.getName());
    System.out.println(c);

    System.out.println(type.equals(c));
    System.out.println("====  testgeneric4b ====");
    FieldEx field = BeanUtils.getField(GenericTypeTemplateTest.class, "field1");
    System.out.println(field.getType().equals(c));
    System.out.println(field.getGenericType().equals(c)); // 当不是泛型时,返回的是class对象
    System.out.println(field.getType());
    System.out.println(field.getGenericType());
    System.out.println(type);
    System.out.println(field.getGenericType().equals(type));

    System.out.println("====  testgeneric4c ====");
    field = BeanUtils.getField(GenericTypeTemplateTest.class, "field2");
    System.out.println(field.getType());
    System.out.println(field.getGenericType());
    type = field.getGenericType();
    System.out.println("isRawArray:" + GenericUtils.isRawArray(type));
    System.out.println("rawType:" + GenericUtils.getRawClass(type));
    System.out.println(GenericUtils.getRawClass(type).equals(field.getType()));
  }
 public Injectable getInjectable(
     final ComponentContext ic, final Context context, final Type type) {
   if (type.equals(ApiUrlBuilder.class)) {
     return this;
   }
   return null;
 }
Ejemplo n.º 11
0
  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    if (!super.equals(o)) {
      return false;
    }

    NewExpression that = (NewExpression) o;

    if (arguments != null ? !arguments.equals(that.arguments) : that.arguments != null) {
      return false;
    }
    if (memberDeclarations != null
        ? !memberDeclarations.equals(that.memberDeclarations)
        : that.memberDeclarations != null) {
      return false;
    }
    if (!type.equals(that.type)) {
      return false;
    }

    return true;
  }
 protected boolean containsType(Type type) {
   for (Type providedType : providedHandlers.keySet()) {
     if (providedType.equals(type)) {
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 13
0
 public static <T> Class<T> getGenericType(Class<?> klass, int index) {
   Type genericSuperclass = klass.getGenericSuperclass();
   if (genericSuperclass instanceof ParameterizedType)
     return (Class<T>)
         ((ParameterizedType) klass.getGenericSuperclass()).getActualTypeArguments()[index];
   if (genericSuperclass.equals(Object.class)) return null;
   return getGenericType(klass.getSuperclass(), index);
 }
Ejemplo n.º 14
0
  /**
   * Checks if the subject type may be implicitly cast to the target parameterized type following
   * the Java generics rules.
   *
   * @param type the subject type to be assigned to the target type
   * @param toParameterizedType the target parameterized type
   * @return true if <code>type</code> is assignable to <code>toType</code>.
   */
  private static boolean isAssignable(
      Type type, ParameterizedType toParameterizedType, Map<TypeVariable<?>, Type> typeVarAssigns) {
    if (type == null) {
      return true;
    }

    // only a null type can be assigned to null type which
    // would have cause the previous to return true
    if (toParameterizedType == null) {
      return false;
    }

    // all types are assignable to themselves
    if (toParameterizedType.equals(type)) {
      return true;
    }

    // get the target type's raw type
    Class<?> toClass = getRawType(toParameterizedType);
    // get the subject type's type arguments including owner type arguments
    // and supertype arguments up to and including the target class.
    Map<TypeVariable<?>, Type> fromTypeVarAssigns = getTypeArguments(type, toClass, null);

    // null means the two types are not compatible
    if (fromTypeVarAssigns == null) {
      return false;
    }

    // compatible types, but there's no type arguments. this is equivalent
    // to comparing Map< ?, ? > to Map, and raw types are always assignable
    // to parameterized types.
    if (fromTypeVarAssigns.isEmpty()) {
      return true;
    }

    // get the target type's type arguments including owner type arguments
    Map<TypeVariable<?>, Type> toTypeVarAssigns =
        getTypeArguments(toParameterizedType, toClass, typeVarAssigns);

    // now to check each type argument
    for (Map.Entry<TypeVariable<?>, Type> entry : toTypeVarAssigns.entrySet()) {
      Type toTypeArg = entry.getValue();
      Type fromTypeArg = fromTypeVarAssigns.get(entry.getKey());

      // parameters must either be absent from the subject type, within
      // the bounds of the wildcard type, or be an exact match to the
      // parameters of the target type.
      if (fromTypeArg != null
          && !toTypeArg.equals(fromTypeArg)
          && !(toTypeArg instanceof WildcardType
              && isAssignable(fromTypeArg, toTypeArg, typeVarAssigns))) {
        return false;
      }
    }

    return true;
  }
 protected Type rightTypeToGet(Type type) {
   for (Type providedType : providedHandlers.keySet()) {
     if (providedType.equals(type)) {
       return providedType;
     }
   }
   // Did not work...
   return type;
 }
Ejemplo n.º 16
0
  /** Returns true if {@code a} and {@code b} are equal. */
  public static boolean equals(Type a, Type b) {
    if (a == b) {
      // also handles (a == null && b == null)
      return true;

    } else if (a instanceof Class) {
      // Class already specifies equals().
      return a.equals(b);

    } else if (a instanceof ParameterizedType) {
      if (!(b instanceof ParameterizedType)) {
        return false;
      }

      // TODO: save a .clone() call
      ParameterizedType pa = (ParameterizedType) a;
      ParameterizedType pb = (ParameterizedType) b;
      return equal(pa.getOwnerType(), pb.getOwnerType())
          && pa.getRawType().equals(pb.getRawType())
          && Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());

    } else if (a instanceof GenericArrayType) {
      if (!(b instanceof GenericArrayType)) {
        return false;
      }

      GenericArrayType ga = (GenericArrayType) a;
      GenericArrayType gb = (GenericArrayType) b;
      return equals(ga.getGenericComponentType(), gb.getGenericComponentType());

    } else if (a instanceof WildcardType) {
      if (!(b instanceof WildcardType)) {
        return false;
      }

      WildcardType wa = (WildcardType) a;
      WildcardType wb = (WildcardType) b;
      return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
          && Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());

    } else if (a instanceof TypeVariable) {
      if (!(b instanceof TypeVariable)) {
        return false;
      }
      TypeVariable<?> va = (TypeVariable<?>) a;
      TypeVariable<?> vb = (TypeVariable<?>) b;
      return va.getGenericDeclaration() == vb.getGenericDeclaration()
          && va.getName().equals(vb.getName());

    } else {
      // This isn't a type we support. Could be a generic array type,
      // wildcard type, etc.
      return false;
    }
  }
Ejemplo n.º 17
0
 public static Class<?> getParamType(Type type, int i) {
   if (type.equals(Object.class)) return Object.class;
   ParameterizedType aType = (ParameterizedType) type;
   Object typeArg = aType.getActualTypeArguments()[i];
   if (typeArg.getClass().equals(Class.class)) {
     return (Class<?>) typeArg;
   } else {
     ParameterizedType subType = (ParameterizedType) typeArg;
     return (Class<?>) subType.getRawType();
   }
 }
Ejemplo n.º 18
0
 @Override
 public boolean equals(Object obj) {
   if (this == obj) return true;
   if (obj == null) return false;
   if (getClass() != obj.getClass()) return false;
   JavaType other = (JavaType) obj;
   if (type == null) {
     if (other.type != null) return false;
   } else if (!type.equals(other.type)) return false;
   return true;
 }
Ejemplo n.º 19
0
  public void outject(@Observes MethodExecuted event, Result result, MethodInfo methodInfo) {

    Type returnType = event.getMethodReturnType();

    if (!returnType.equals(Void.TYPE)) {
      String name = extractor.nameFor(returnType);
      Object value = methodInfo.getResult();
      logger.debug("outjecting {}={}", name, value);
      result.include(name, value);
    }
  }
Ejemplo n.º 20
0
 /**
  * Method to test equality.
  *
  * @return true if this object is logically equal to the specified object, false otherwise.
  */
 @Override
 public boolean equals(Object o) {
   if (o == this) {
     return true;
   }
   if (!(o instanceof TypeToken<?>)) {
     return false;
   }
   TypeToken<?> t = (TypeToken<?>) o;
   return type.equals(t.type);
 }
Ejemplo n.º 21
0
 private boolean shouldTypeBeAdded(final Type t2, final ParameterizedType parameterizedType) {
   if (!(t2 instanceof TypeVariable)) {
     return true;
   }
   TypeVariable<?> typeVariable = (TypeVariable<?>) t2;
   final Type[] bounds = typeVariable.getBounds();
   for (Type bound : bounds) {
     if (bound instanceof ParameterizedType && bound.equals(parameterizedType)) {
       return false;
     }
   }
   return true;
 }
Ejemplo n.º 22
0
  static boolean equivalentTypes(
      Type a, Class ac, Annotations aAnnotations, Type b, Class bc, Annotations bAnnotations) {
    if (a.equals(b)) {
      return true;
    }

    int as = getIntegralSize(a, ac, aAnnotations);
    int bs = getIntegralSize(b, bc, bAnnotations);

    // System.out.println("a = " + a + ", b = " + b + ", as = " + as + ", bs = " + bs + ", equiv = "
    // + (as != -1 && as == bs));
    return as != -1 && as == bs;
  }
Ejemplo n.º 23
0
  private static boolean isParameterizedTypeAssignable(
      ParameterizedType supertype, ParameterizedType type) {
    Type rawSupertype = supertype.getRawType();
    Type rawType = type.getRawType();

    if (!rawSupertype.equals(rawType)) {
      // short circuit when class raw types are unassignable
      if (rawSupertype instanceof Class<?>
          && rawType instanceof Class<?>
          && !(((Class<?>) rawSupertype).isAssignableFrom((Class<?>) rawType))) {
        return false;
      }

      return isSuperAssignable(supertype, type);
    }

    Type[] supertypeArgs = supertype.getActualTypeArguments();
    Type[] typeArgs = type.getActualTypeArguments();

    if (supertypeArgs.length != typeArgs.length) {
      return false;
    }

    for (int i = 0; i < supertypeArgs.length; i++) {
      Type supertypeArg = supertypeArgs[i];
      Type typeArg = typeArgs[i];

      if (supertypeArg instanceof WildcardType) {
        if (!isWildcardTypeAssignable((WildcardType) supertypeArg, typeArg)) {
          return false;
        }
      } else if (!supertypeArg.equals(typeArg)) {
        return false;
      }
    }

    return true;
  }
Ejemplo n.º 24
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;
 }
Ejemplo n.º 25
0
 /**
  * @param types - Array of types to resolve. The unresolved type is replaced in the array with the
  *     resolved type.
  * @param containingType - the shallowest type in the hierarchy where type is defined.
  * @return true if any of the types were resolved.
  */
 private static boolean resolve(Type[] types, Type containingType) {
   boolean modified = false;
   for (int i = 0; i < types.length; ++i) {
     Type t = types[i];
     if (!(t instanceof Class)) {
       modified = true;
       final Type resolved = resolve(t, containingType);
       if (!resolved.equals(t)) {
         types[i] = resolved;
         modified = true;
       }
     }
   }
   return modified;
 }
Ejemplo n.º 26
0
 @Override
 public boolean equals(Object o) {
   if (!(o instanceof ResolutionKey)) {
     return false;
   }
   ResolutionKey other = (ResolutionKey) o;
   // Object identity comparison intentional
   if (domainObject != other.domainObject) {
     return false;
   }
   if (!requestedType.equals(other.requestedType)) {
     return false;
   }
   return true;
 }
Ejemplo n.º 27
0
 public static List<Class> findAllClasses(Class superclass, String... packages)
     throws IOException, ClassNotFoundException {
   List<Class> result = new ArrayList<Class>();
   for (String packge : packages) {
     List<Class> l = Utils.getClassesForPackage(packge);
     for (Class c : l) {
       String className = c.getName();
       Type type = Class.forName(className).getGenericSuperclass();
       if (type != null && (type.equals(superclass) || result.contains(type))) {
         Class classClass = Class.forName(className).asSubclass(superclass);
         result.add(classClass);
       }
     }
   }
   return result;
 }
  private static Type[] getParamType(Class<?> cls, Class<?> matchRawType) {

    Type[] gis = cls.getGenericInterfaces();
    for (int i = 0; i < gis.length; i++) {
      Type type = gis[i];
      if (type instanceof ParameterizedType) {
        ParameterizedType paramType = (ParameterizedType) type;
        Type rawType = paramType.getRawType();
        if (rawType.equals(matchRawType)) {

          return paramType.getActualTypeArguments();
        }
      }
    }
    return null;
  }
Ejemplo n.º 29
0
  /**
   * Creates {@link TypeInformation} for the given {@link Type}.
   *
   * @param fieldType the field type
   * @return the type information
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  protected TypeInformation<?> createInfo(Type fieldType) {

    if (fieldType.equals(this.type)) {
      return this;
    }

    if (fieldType instanceof Class) {
      return new ClassTypeInformation((Class<?>) fieldType);
    }

    Map<TypeVariable, Type> variableMap =
        GenericTypeResolver.getTypeVariableMap(resolveType(fieldType));

    if (fieldType instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) fieldType;
      return new ParameterizedTypeInformation(parameterizedType, this);
    }

    if (fieldType instanceof TypeVariable) {
      TypeVariable<?> variable = (TypeVariable<?>) fieldType;
      return new TypeVariableTypeInformation(variable, type, this, variableMap);
    }

    if (fieldType instanceof GenericArrayType) {
      return new GenericArrayTypeInformation((GenericArrayType) fieldType, this);
    }

    if (fieldType instanceof WildcardType) {

      WildcardType wildcardType = (WildcardType) fieldType;
      Type[] bounds = wildcardType.getLowerBounds();

      if (bounds.length > 0) {
        return createInfo(bounds[0]);
      }

      bounds = wildcardType.getUpperBounds();

      if (bounds.length > 0) {
        return createInfo(bounds[0]);
      }
    }

    throw new IllegalArgumentException();
  }
Ejemplo n.º 30
0
    private boolean matchesArgs(Type[] parameterTypes, Annotation[][] anns, int offset) {
      int totalArgs = offset;
      for (int i = 0, n = templateArguments == null ? 0 : templateArguments.length; i < n; i++) {
        if (totalArgs >= parameterTypes.length) {
          return false;
        }

        Type paramType = parameterTypes[offset + i];

        TemplateArg arg = templateArguments[i];
        if (arg instanceof TypeRef) {
          if (!paramType.equals(Class.class)) {
            return false;
          }
        } else if (arg instanceof Constant) {
          try {
            getTypeClass(paramType).cast(((Constant) arg).value);
          } catch (ClassCastException ex) {
            return false;
          }
        }
        totalArgs++;
      }

      for (int i = 0, n = paramTypes == null ? 0 : paramTypes.length; i < n; i++) {
        if (totalArgs >= parameterTypes.length) {
          return false;
        }

        TypeRef paramType = paramTypes[i];
        Type parameterType = parameterTypes[totalArgs];
        if (!paramType.matches(parameterType, annotations(anns == null ? null : anns[i]))) {
          return false;
        }

        totalArgs++;
      }

      if (totalArgs != parameterTypes.length) {
        BridJ.error("Not enough args for " + this);
        return false;
      }

      return true;
    }