示例#1
1
  /**
   * Determines the key type for a Map.
   *
   * @param type The parametrized type.
   * @param path The path to the type, used in exception message.
   * @return The key type.
   */
  public static Type[] mapTypes(Type type, String path) {
    if (type instanceof Class) {
      Class c = (Class) type;
      type = c.getGenericSuperclass();
      if (!(isGenericMap(type))) {
        Type[] types = c.getGenericInterfaces();
        if (types != null && types.length > 0) {
          for (Type t : types) {
            if (isGenericMap(t)) {
              type = t;
              break;
            }
          }
        }
      }
    }

    if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;
      Class<?> rawType = (Class<?>) parameterizedType.getRawType();
      if (Map.class.isAssignableFrom(rawType)) {
        return parameterizedType.getActualTypeArguments();
      }
    }

    throw new CollectionExpressionException(
        "The method or member ["
            + path
            + "] returns a simple Map. Unable to determine the "
            + "types of the Map. Please make this method or member generic so that the correct type can be determined.");
  }
 @Override
 public <T> void extract(ModelSchemaExtractionContext<T> extractionContext) {
   Type type = extractionContext.getType().getType();
   if (!(type instanceof Class)) {
     return;
   }
   Class<?> contractType = (Class<?>) type;
   if (!contractType.isInterface()) {
     return;
   }
   if (contractType.getGenericInterfaces().length != 1) {
     return;
   }
   Type superType = contractType.getGenericInterfaces()[0];
   if (!(superType instanceof ParameterizedType)) {
     return;
   }
   ParameterizedType parameterizedSuperType = (ParameterizedType) superType;
   if (!parameterizedSuperType.getRawType().equals(ModelMap.class)) {
     return;
   }
   ModelType<?> elementType = ModelType.of(parameterizedSuperType.getActualTypeArguments()[0]);
   Class<?> proxyImpl = generator.generate(ModelMapGroovyDecorator.Managed.class, contractType);
   extractionContext.found(
       new SpecializedMapSchema<T>(extractionContext.getType(), elementType, proxyImpl));
 }
 private void writeObject(
     ContentValues values, Object object, String columnName, ParameterizedType fieldType)
     throws IOException {
   if (object == null) return;
   final Type rawType = fieldType.getRawType();
   if (!(rawType instanceof Class)) throw new UnsupportedOperationException();
   final Class rawCls = (Class) rawType;
   if (List.class.isAssignableFrom(rawCls)) {
     values.put(
         columnName,
         LoganSquare.serialize((List) object, (Class) fieldType.getActualTypeArguments()[0]));
   } else if (Map.class.isAssignableFrom(rawCls)) {
     //noinspection unchecked
     values.put(
         columnName,
         LoganSquare.serialize((Map) object, (Class) fieldType.getActualTypeArguments()[1]));
   } else if (rawCls.isArray()) {
     final Class componentType = rawCls.getComponentType();
     values.put(
         columnName,
         LoganSquare.serialize((List) Arrays.asList((Object[]) object), componentType));
   } else {
     values.put(columnName, LoganSquare.serialize(object));
   }
 }
示例#4
0
  /**
   * Returns the component types of the given type. Returns <code>null</code> if given type does not
   * have a single component type. For example the following types all have the component-type
   * MyClass:
   *
   * <ul>
   *   <li>MyClass[]
   *   <li>List&lt;MyClass&gt;
   *   <li>Foo&lt;? extends MyClass&gt;
   *   <li>Bar&lt;? super MyClass&gt;
   *   <li>&lt;T extends MyClass&gt; T[]
   * </ul>
   */
  public static Class[] getComponentTypes(Type type, Class implClass) {
    if (type instanceof Class) {
      Class clazz = (Class) type;
      if (clazz.isArray()) {
        return new Class[] {clazz.getComponentType()};
      }
    } else if (type instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) type;

      Type[] generics = pt.getActualTypeArguments();

      if (generics.length == 0) {
        return null;
      }

      Class[] types = new Class[generics.length];

      for (int i = 0; i < generics.length; i++) {
        types[i] = getRawType(generics[i], implClass);
      }
      return types;
    } else if (type instanceof GenericArrayType) {
      GenericArrayType gat = (GenericArrayType) type;

      Class rawType = getRawType(gat.getGenericComponentType(), implClass);
      if (rawType == null) {
        return null;
      }

      return new Class[] {rawType};
    }
    return null;
  }
示例#5
0
 // 反射获取T的simpleName
 public BaseService() {
   Type type = this.getClass().getGenericSuperclass();
   ParameterizedType pt = (ParameterizedType) type;
   Type[] types = pt.getActualTypeArguments();
   clazz = (Class<T>) types[0];
   Tname = clazz.getSimpleName();
 }
示例#6
0
文件: Lang.java 项目: flymichael/nutz
 /** 获取一个Type类型实际对应的Class */
 @SuppressWarnings("rawtypes")
 public static Class<?> getTypeClass(Type type) {
   Class<?> clazz = null;
   if (type instanceof Class<?>) {
     clazz = (Class<?>) type;
   } else if (type instanceof ParameterizedType) {
     ParameterizedType pt = (ParameterizedType) type;
     clazz = (Class<?>) pt.getRawType();
   } else if (type instanceof GenericArrayType) {
     GenericArrayType gat = (GenericArrayType) type;
     Class<?> typeClass = getTypeClass(gat.getGenericComponentType());
     return Array.newInstance(typeClass, 0).getClass();
   } else if (type instanceof TypeVariable) {
     TypeVariable tv = (TypeVariable) type;
     Type[] ts = tv.getBounds();
     if (ts != null && ts.length > 0) return getTypeClass(ts[0]);
   } else if (type instanceof WildcardType) {
     WildcardType wt = (WildcardType) type;
     Type[] t_low = wt.getLowerBounds(); // 取其下界
     if (t_low.length > 0) return getTypeClass(t_low[0]);
     Type[] t_up = wt.getUpperBounds(); // 没有下界?取其上界
     return getTypeClass(t_up[0]); // 最起码有Object作为上界
   }
   return clazz;
 }
示例#7
0
 public static Class getFieldGenericType(Field field) {
   if (ParameterizedType.class.isAssignableFrom(field.getGenericType().getClass())) {
     ParameterizedType genericType = (ParameterizedType) field.getGenericType();
     return (Class) genericType.getActualTypeArguments()[0];
   }
   return Void.class;
 }
  @SuppressWarnings("unchecked")
  static Class<? extends Event<?>> getEventClass(Class<?> handlerClass) {

    for (Class<?> i : handlerClass.getInterfaces()) {
      if (EventHandler.class.equals(i)) {
        for (Type t : handlerClass.getGenericInterfaces()) {
          if (t instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) t;
            if (EventHandler.class.equals(pt.getRawType())) {

              return (Class<? extends Event<?>>) pt.getActualTypeArguments()[0];
            }
          }
        }
      } else if (EventHandler.class.isAssignableFrom(i)) {
        return getEventClass((Class<? extends EventHandler<?>>) i);
      }
    }

    if (EventHandler.class.isAssignableFrom(handlerClass.getSuperclass())) {
      return getEventClass((Class<?>) handlerClass.getSuperclass());
    }

    return null;
  }
 @Override
 protected void found(final Class<ActEventListener> target, final App app) {
     final EventBus bus = app.eventBus();
     ParameterizedType ptype = null;
     Type superType = target.getGenericSuperclass();
     while (ptype == null) {
         if (superType instanceof ParameterizedType) {
             ptype = (ParameterizedType) superType;
         } else {
             if (Object.class == superType) {
                 logger.warn("Event listener registration failed: cannot find generic information for %s", target.getName());
                 return;
             }
             superType = ((Class) superType).getGenericSuperclass();
         }
     }
     Type[] ca = ptype.getActualTypeArguments();
     for (Type t : ca) {
         if (t instanceof Class) {
             final Class tc = (Class) t;
             if (ActEvent.class.isAssignableFrom(tc)) {
                 app.eventBus().bind(AppEventId.DEPENDENCY_INJECTOR_LOADED, new AppEventListenerBase() {
                     @Override
                     public void on(EventObject event) throws Exception {
                         ActEventListener listener = (ActEventListener) app.newInstance(target);
                         bus.bind(tc, listener);
                     }
                 });
                 return;
             }
         }
     }
 }
 private Object convert(
     Type targetType, Object sourceObject, Action<? super SourceObjectMapping> mapping) {
   if (targetType instanceof ParameterizedType) {
     ParameterizedType parameterizedTargetType = (ParameterizedType) targetType;
     if (parameterizedTargetType.getRawType() instanceof Class) {
       Class<?> rawClass = (Class<?>) parameterizedTargetType.getRawType();
       if (Iterable.class.isAssignableFrom(rawClass)) {
         Type targetElementType = getElementType(parameterizedTargetType, 0);
         return convertCollectionInternal(
             rawClass, targetElementType, (Iterable<?>) sourceObject, mapping);
       }
       if (Map.class.isAssignableFrom(rawClass)) {
         Type targetKeyType = getElementType(parameterizedTargetType, 0);
         Type targetValueType = getElementType(parameterizedTargetType, 1);
         return convertMap(
             rawClass, targetKeyType, targetValueType, (Map<?, ?>) sourceObject, mapping);
       }
     }
   }
   if (targetType instanceof Class) {
     if (((Class) targetType).isPrimitive()) {
       return sourceObject;
     }
     return adapt((Class) targetType, sourceObject, mapping);
   }
   throw new UnsupportedOperationException(
       String.format("Cannot convert object of %s to %s.", sourceObject.getClass(), targetType));
 }
示例#11
0
 public static Generic fromType(Type type) {
   Generic generic = new Generic();
   if (!(type instanceof ParameterizedType)) {
     ThriftType thriftType = ThriftType.fromJavaType(type);
     generic.setJavaClass(thriftType.getJavaClass());
     generic.setJavaTypeName(thriftType.getJavaTypeName());
     generic.setValue(thriftType.getValue());
     generic.setWarpperClassName(thriftType.getWarpperClassName());
     generic.setType(thriftType.getType());
     return generic;
   }
   ThriftType thriftType = ThriftType.fromJavaType(type);
   generic.setValue(thriftType.getValue());
   ParameterizedType parameterizedType = (ParameterizedType) type;
   Type[] types = parameterizedType.getActualTypeArguments();
   for (Type typeArgument : types) {
     if (typeArgument instanceof ParameterizedType) {
       generic.addGeneric(fromType(typeArgument));
       continue;
     }
     ThriftType typeArgumentThriftType = ThriftType.fromJavaType((Class<?>) typeArgument);
     if (typeArgumentThriftType.isStruct()) {
       typeArgumentThriftType = typeArgumentThriftType.clone();
       typeArgumentThriftType.setJavaClass((Class<?>) typeArgument);
       typeArgumentThriftType.setValue(((Class<?>) typeArgument).getSimpleName());
     }
     generic.addGeneric(typeArgumentThriftType);
   }
   return generic;
 }
示例#12
0
 @SuppressWarnings({"unchecked", "rawtypes"})
 public GenericDaoImpl() {
   LOGGER.debug("Init Generic Dao - Implement Abstract Facade Into The System");
   Type t = getClass().getGenericSuperclass();
   ParameterizedType pt = (ParameterizedType) t;
   daoType = (Class) pt.getActualTypeArguments()[0];
 }
示例#13
0
  /**
   * Determines the component type. Lists is the first type, Map is the second type, etc.
   *
   * @param type The parametrized type.
   * @param path The path to the type, used in exception message.
   * @return The component type.
   */
  public static Type componentType(Type type, String path) {
    if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;
      Class<?> rawType = (Class<?>) parameterizedType.getRawType();
      if (Map.class.isAssignableFrom(rawType)) {
        return parameterizedType.getActualTypeArguments()[1];
      } else if (Collection.class.isAssignableFrom(rawType)) {
        return parameterizedType.getActualTypeArguments()[0];
      } else {
        throw new CollectionExpressionException("Unknown collection type [" + type + "]");
      }
    } else if (type instanceof GenericArrayType) {
      return ((GenericArrayType) type).getGenericComponentType();
    }

    Class<?> rawType = (Class<?>) type;
    if (Map.class == type || Collection.class == type) {
      throw new CollectionExpressionException(
          "The method or member ["
              + path
              + "] returns a simple "
              + "Map or Collection. Unable to determine the type of the Map or Collection. "
              + "Please make this method generic so that the correct type can be determined.");
    } else if (rawType.isArray()) {
      return rawType.getComponentType();
    }

    return rawType;
  }
  /**
   * To make life easier for the user we will figure out the type of {@link StreamListener} the user
   * passed and based on that setup the correct stream analyzer etc.
   *
   * <p>{@inheritDoc}
   */
  @SuppressWarnings("unchecked")
  @Override
  public void addStreamListener(final StreamListener<? extends Packet> listener) {

    try {
      final Method method = listener.getClass().getMethod("endStream", Stream.class);
      final ParameterizedType parameterizedType =
          (ParameterizedType) method.getGenericParameterTypes()[0];
      final Type[] parameterArgTypes = parameterizedType.getActualTypeArguments();

      // TODO: could actually be more.
      final Type parameterArgType = parameterArgTypes[0];
      final Class<?> parameterArgClass = (Class<?>) parameterArgType;
      if (parameterArgClass.equals(SipPacket.class)) {
        if (this.sipStreamHandler == null) {
          this.sipStreamHandler = new SipStreamHandler(this.framerManager);
        }
        this.sipStreamHandler.addListener((StreamListener<SipPacket>) listener);
      }

    } catch (final ArrayIndexOutOfBoundsException e) {
      throw new RuntimeException("Unable to figure out the paramterized type", e);
    } catch (final SecurityException e) {
      throw new RuntimeException(
          "Unable to access method information due to security constraints", e);
    } catch (final NoSuchMethodException e) {
      throw new RuntimeException("The startStream method doesn't exist. Signature changed?", e);
    } catch (final ClassCastException e) {
      // means that the user had not parameterized the StreamListener
      // interface, which means that we cannot actually detect streams.
      throw new IllegalArgumentException("The supplied listener has not been parameterized");
    }
  }
示例#15
0
  static Class<?> getTypeClass(Type type) {

    if (type instanceof Class<?>) {
      return (Class<?>) type;
    }
    if (type instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) type;
      Class<?> c = (Class<?>) pt.getRawType();
      if (ValuedEnum.class.isAssignableFrom(c)) {
        Type[] types = pt.getActualTypeArguments();
        if (types == null || types.length != 1) {
          c = int.class;
        } else {
          c = getTypeClass(pt.getActualTypeArguments()[0]);
        }
      }
      return c;
    }
    if (type instanceof GenericArrayType) {
      if (Object.class.isAssignableFrom(
          getTypeClass(((GenericArrayType) type).getGenericComponentType()))) {
        return Object[].class;
      }
    }
    throw new UnsupportedOperationException("Unknown type type : " + type.getClass().getName());
  }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      Preference annotation = method.getAnnotation(Preference.class);
      String key = annotation.value();
      String defaultString = annotation.defaultString();
      boolean defaultBoolean = annotation.defaultBoolean();
      int defaultInt = annotation.defaultInt();
      long defaultLong = annotation.defaultLong();
      float defaultFloat = annotation.defaultFloat();

      if (method.getReturnType().equals(StringEntry.class)) {
        return new StringEntry(preferences, key, defaultString);
      } else if (method.getReturnType().equals(FloatEntry.class)) {
        return new FloatEntry(preferences, key, defaultFloat);
      } else if (method.getReturnType().equals(LongEntry.class)) {
        return new LongEntry(preferences, key, defaultLong);
      } else if (method.getReturnType().equals(IntEntry.class)) {
        return new IntEntry(preferences, key, defaultInt);
      } else if (method.getReturnType().equals(BooleanEntry.class)) {
        return new BooleanEntry(preferences, key, defaultBoolean);
      } else if (method.getReturnType().equals(ObjectEntry.class)) {
        if (method.getGenericReturnType() instanceof ParameterizedType) {
          ParameterizedType parameterizedType = (ParameterizedType) method.getGenericReturnType();
          Class<?> type = (Class) parameterizedType.getActualTypeArguments()[0];
          return new ObjectEntry<>(preferences, key, gson, type);
        }
        throw new RuntimeException("ObjectEntries must have a parameter");
      } else {
        return null;
      }
    }
示例#17
0
 @Nullable
 private static TypeWrapper wrap(Type type) {
   if (type == null) {
     return null;
   } else if (type instanceof Class) {
     return new ClassTypeWrapper((Class<?>) type);
   } else if (type instanceof ParameterizedType) {
     ParameterizedType parameterizedType = (ParameterizedType) type;
     return new ParameterizedTypeWrapper(
         toWrappers(parameterizedType.getActualTypeArguments()),
         (ClassTypeWrapper) wrap(parameterizedType.getRawType()),
         wrap(parameterizedType.getOwnerType()));
   } else if (type instanceof WildcardType) {
     WildcardType wildcardType = (WildcardType) type;
     return new WildcardTypeWrapper(
         toWrappers(wildcardType.getUpperBounds()),
         toWrappers(wildcardType.getLowerBounds()),
         type.hashCode());
   } else if (type instanceof TypeVariable) {
     TypeVariable<?> typeVariable = (TypeVariable<?>) type;
     return new TypeVariableTypeWrapper(
         typeVariable.getName(), toWrappers(typeVariable.getBounds()), type.hashCode());
   } else if (type instanceof GenericArrayType) {
     GenericArrayType genericArrayType = (GenericArrayType) type;
     return new GenericArrayTypeWrapper(
         wrap(genericArrayType.getGenericComponentType()), type.hashCode());
   } else {
     throw new IllegalArgumentException("cannot wrap type of type " + type.getClass());
   }
 }
示例#18
0
  /**
   * Creates the type, it's private so you must use fromType.
   *
   * @param type
   */
  private JavaType(Type type) {

    // the type
    this.type = type;

    // parameterized?
    parameterizedType =
        ParameterizedType.class.isInstance(type) ? ParameterizedType.class.cast(type) : null;

    // generic info
    genericInfo = parameterizedType != null;

    // get class
    if (Class.class.isInstance(type)) {
      clazz = Class.class.cast(type);
    } else if (parameterizedType != null) {
      clazz = Class.class.cast(parameterizedType.getRawType());
    } else {
      clazz = null;
    }

    // component type
    if (clazz != null && clazz.getComponentType() != null) {
      componentType = clazz.getComponentType();
    }

    // instantiable
    instantiable = clazz != null;

    // typeParameters
    typeParameters = parameterizedType != null ? parameterizedType.getActualTypeArguments() : null;

    // genericInfo
    genericInfo = typeParameters != null;
  }
 public void testResolveToGenericArrayType() {
   GenericArrayType arrayType =
       (GenericArrayType) new Holder<List<int[][]>[]>() {}.getContentType();
   ParameterizedType listType = (ParameterizedType) arrayType.getGenericComponentType();
   assertEquals(List.class, listType.getRawType());
   assertEquals(Types.newArrayType(int[].class), listType.getActualTypeArguments()[0]);
 }
 private String nameFor(ParameterizedType type) {
   Class<?> raw = (Class<?>) type.getRawType();
   if (Collection.class.isAssignableFrom(raw)) {
     return nameFor(type.getActualTypeArguments()[0]) + "List";
   }
   return nameFor(raw);
 }
示例#21
0
  @SuppressWarnings("unchecked")
  private Object toValue(Object bean, Field field, XMLNode node) throws Exception {
    Class<?> type = field.getType();

    field.setAccessible(true);
    Object current = field.get(bean);
    if (current != null) type = current.getClass();

    if (Collection.class.isAssignableFrom(type)) {
      Type eleParamType = Object.class;
      ParameterizedType paramType = (ParameterizedType) field.getGenericType();
      if (paramType.getActualTypeArguments().length > 0) {
        eleParamType = paramType.getActualTypeArguments()[0];
      }
      Object[] array = (Object[]) toArrayValues((Class<?>) eleParamType, node);
      Collection collection = null;

      if (current != null && current instanceof Collection) {
        collection = (Collection) current;
      } else if (type.isInterface()) {
        collection = new ArrayList<Object>();
      } else {
        collection = (Collection) type.newInstance();
      }
      Collections.addAll(collection, array);
      return collection;
    }

    if (type.isArray()) return toArrayValues(type, node);

    return toValue(type, node);
  }
            @Override
            public void map(
                ServiceReference<ModelAdapterBuilder> serviceReference, Emitter<String> emitter) {

              Registry registry = RegistryUtil.getRegistry();

              ModelAdapterBuilder modelAdapterBuilder = registry.getService(serviceReference);

              Type genericInterface =
                  ReflectionUtil.getGenericInterface(
                      modelAdapterBuilder, ModelAdapterBuilder.class);

              if ((genericInterface == null) || !(genericInterface instanceof ParameterizedType)) {

                return;
              }

              ParameterizedType parameterizedType = (ParameterizedType) genericInterface;

              Type[] typeArguments = parameterizedType.getActualTypeArguments();

              if (ArrayUtil.isEmpty(typeArguments) || (typeArguments.length != 2)) {

                return;
              }

              try {
                Class adapteeModelClass = (Class) typeArguments[0];
                Class adaptedModelClass = (Class) typeArguments[1];

                emitter.emit(getKey(adapteeModelClass, adaptedModelClass));
              } catch (ClassCastException cce) {
                return;
              }
            }
 /**
  * Infer value type in one collection type
  *
  * @param genericType
  * @return
  */
 public static Type inferElementTypeIn(Type collectionType) {
   if (collectionType instanceof Class) {
     return Object.class;
   } else if (collectionType instanceof ParameterizedType) {
     ParameterizedType parameterizedCollectionType = (ParameterizedType) collectionType;
     Type collectionValueType = parameterizedCollectionType.getActualTypeArguments()[0];
     if (collectionValueType instanceof Class) {
       return (Class) collectionValueType;
     } else if (collectionValueType instanceof ParameterizedType) {
       ParameterizedType type = (ParameterizedType) collectionValueType;
       return type.getRawType();
     } else if (collectionValueType instanceof WildcardType) {
       throw new UnusableTypeException(
           "we can't infer element type in widlcard type " + collectionType.toString());
     } else if (collectionValueType instanceof TypeVariable) {
       throw new UnusableTypeException(
           "we can't infer element type in type variable " + collectionType.toString());
     }
   } else if (collectionType instanceof WildcardType) {
     throw new UnusableTypeException(
         "we can't infer element type in widlcard type " + collectionType.toString());
   } else if (collectionType instanceof TypeVariable) {
     throw new UnusableTypeException(
         "we can't infer element type in type variable " + collectionType.toString());
   }
   throw new UnusableTypeException("we can't infer element type in " + collectionType.toString());
 }
示例#24
0
 /**
  * Returns the value of the given {@link TypeVariable} as a {@link GenericType}.
  *
  * @param variable must parameterize this type or one of it's super types
  * @return the actual value of the given {@link TypeVariable} as a {@link GenericType}
  * @throws IllegalArgumentException if the variable does not parameterize this type
  * @throws UnsupportedOperationException if the type parameter resolution is not supported for
  *     this type
  */
 public GenericType getTypeParameter(TypeVariable<? extends Class<?>> variable)
     throws IllegalArgumentException, IllegalStateException {
   assertThatTypeVariableDoesParameterizeAClass(variable);
   GenericType result = null;
   if (type instanceof Class<?>) {
     Class<?> cls = (Class<?>) type;
     // Class<?> parameterizedClass = (Class<?>)
     // variable.getGenericDeclaration();
     // // Break-Condition
     // if (parameterizedClass.equals(cls)) {
     // GenericType result = new GenericType(mapping, variable);
     // return result;
     // }
     VariableMapping aMapping = resolveTypeVariableInClass(variable, cls, mapping);
     if (aMapping != null) {
       result = getGenericType(aMapping, variable);
     }
   } else if (type instanceof ParameterizedType) {
     ParameterizedType pType = (ParameterizedType) type;
     Class<?> rawType = (Class<?>) pType.getRawType();
     VariableMapping aMapping = resolveTypeVariableInClass(variable, rawType, mapping);
     if (aMapping != null) {
       result = getGenericType(aMapping, variable);
     }
   } else {
     throw new UnsupportedOperationException(
         String.format("Type parameter resolution not supported for %s", type));
   }
   if (result == null) {
     throw new IllegalArgumentException(
         String.format("%s does not parameterize this type %s!", variable, type));
   } else {
     return result;
   }
 }
示例#25
0
文件: Lang.java 项目: flymichael/nutz
 /**
  * 返回一个type的泛型数组, 如果没有, 则直接返回null
  *
  * @param type
  * @return
  */
 public static Type[] getGenericsTypes(Type type) {
   if (type instanceof ParameterizedType) {
     ParameterizedType pt = (ParameterizedType) type;
     return pt.getActualTypeArguments();
   }
   return null;
 }
示例#26
0
  private static GenericType getFieldType(
      VariableMapping currentMapping, Class<?> startClass, String fieldname) {
    Type type = null;
    Field field = null; // e.g. BClass<String, Integer> bObject;
    {
      Class<?> ownerClass = startClass;
      findfield:
      while (true) {
        Field[] fields = ownerClass.getDeclaredFields();
        for (Field f : fields) {
          if (f.getName().equals(fieldname)) {
            field = f;
            break findfield;
          }
        }
        // field not found so far
        // -> search superclass
        Type superType = ownerClass.getGenericSuperclass();
        if (superType instanceof ParameterizedType) {
          ParameterizedType parameterizedSuperType = (ParameterizedType) superType;
          currentMapping = new VariableMapping(currentMapping, parameterizedSuperType);
          ownerClass = (Class<?>) parameterizedSuperType.getRawType();
        } else if (superType instanceof Class<?>) {
          ownerClass = (Class<?>) superType;
        } else {
          throw new IllegalStateException();
        }
      }
    }

    type = field.getGenericType(); // e.g. BClass<String, Integer>

    return getGenericType(currentMapping, type);
  }
 /**
  * Gets the specific Pojo class.
  *
  * @return the specific Pojo class
  */
 protected Class getDomainClass() {
   if (domainClass == null) {
     ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();
     domainClass = (Class) thisType.getActualTypeArguments()[0];
   }
   return domainClass;
 }
示例#28
0
  public static Class<?> getRawType(Type type) {
    if (type instanceof Class<?>) {
      // type is a normal class.
      return (Class<?>) type;

    } else if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;

      // I'm not exactly sure why getRawType() returns Type instead of Class.
      // Neal isn't either but suspects some pathological case related
      // to nested classes exists.
      Type rawType = parameterizedType.getRawType();
      // checkArgument(rawType instanceof Class,
      // "Expected a Class, but <%s> is of type %s", type, type.getClass().getName());
      return (Class<?>) rawType;

    } else if (type instanceof GenericArrayType) {
      // TODO: Is this sufficient?
      return Object[].class;

    } else if (type instanceof TypeVariable) {
      // we could use the variable's bounds, but that'll won't work if there are multiple.
      // having a raw type that's more general than necessary is okay
      return Object.class;

    } else {
      throw new IllegalArgumentException(
          "Expected a Class, ParameterizedType, or "
              + "GenericArrayType, but <"
              + type
              + "> is of type "
              + type.getClass().getName());
    }
  }
示例#29
0
  @SuppressWarnings("unchecked")
  private static Class<?> getRawType(Type type) {
    if (type instanceof Class<?>) {
      // type is a normal class.
      return (Class<?>) type;
    } else if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;

      // I'm not exactly sure why getRawType() returns Type instead of Class.
      // Neal isn't either but suspects some pathological case related
      // to nested classes exists.
      Type rawType = parameterizedType.getRawType();
      if (rawType instanceof Class<?>) {
        return (Class<?>) rawType;
      }
      throw buildUnexpectedTypeError(rawType, Class.class);
    } else if (type instanceof GenericArrayType) {
      GenericArrayType genericArrayType = (GenericArrayType) type;

      // TODO(jleitch): This is not the most efficient way to handle generic
      // arrays, but is there another way to extract the array class in a
      // non-hacky way (i.e. using String value class names- "[L...")?
      Object rawArrayType =
          Array.newInstance(getRawType(genericArrayType.getGenericComponentType()), 0);
      return rawArrayType.getClass();
    } else {
      throw buildUnexpectedTypeError(type, ParameterizedType.class, GenericArrayType.class);
    }
  }
  private Type getActualType() {
    Type genericSuperclass = this.getClass().getGenericSuperclass();
    ParameterizedType pt = (ParameterizedType) genericSuperclass;
    Type type = pt.getActualTypeArguments()[0];

    return type;
  }