Java Code Examples for java.lang.reflect.ParameterizedType

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project android_8, under directory /src/com/google/gson/internal/.

Source file: $Gson$Types.java

  21 
vote

/** 
 * Returns a two element array containing this map's key and value types in positions 0 and 1 respectively.
 */
public static Type[] getMapKeyAndValueTypes(Type context,Class<?> contextRawType){
  if (context == Properties.class) {
    return new Type[]{String.class,String.class};
  }
  Type mapType=getSupertype(context,contextRawType,Map.class);
  ParameterizedType mapParameterizedType=(ParameterizedType)mapType;
  return mapParameterizedType.getActualTypeArguments();
}
 

Example 2

From project arquillian-core, under directory /core/impl-base/src/main/java/org/jboss/arquillian/core/impl/.

Source file: InjectionPointImpl.java

  18 
vote

@Override public Type getType(){
  ParameterizedType type=(ParameterizedType)field.getGenericType();
  if (type.getActualTypeArguments()[0] instanceof ParameterizedType) {
    ParameterizedType first=(ParameterizedType)type.getActualTypeArguments()[0];
    return (Class<?>)first.getRawType();
  }
 else {
    return (Class<?>)type.getActualTypeArguments()[0];
  }
}
 

Example 3

From project arquillian-extension-drone, under directory /drone-impl/src/main/java/org/jboss/arquillian/drone/impl/.

Source file: DroneRegistrar.java

  18 
vote

private static Class<?> getFirstGenericParameterType(Class<?> clazz,Class<?> rawType){
  for (  Type interfaceType : clazz.getGenericInterfaces()) {
    if (interfaceType instanceof ParameterizedType) {
      ParameterizedType ptype=(ParameterizedType)interfaceType;
      if (rawType.isAssignableFrom((Class<?>)ptype.getRawType())) {
        return (Class<?>)ptype.getActualTypeArguments()[0];
      }
    }
  }
  return null;
}
 

Example 4

From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/client/execution/.

Source file: DefaultRequestEnrichmentService.java

  18 
vote

private boolean isType(RequestFilter<?> filter,Type expectedType){
  Type[] interfaces=filter.getClass().getGenericInterfaces();
  for (  Type type : interfaces) {
    if (type instanceof ParameterizedType) {
      ParameterizedType parametrizedType=(ParameterizedType)type;
      if (parametrizedType.getRawType() == RequestFilter.class) {
        return parametrizedType.getActualTypeArguments()[0] == expectedType;
      }
    }
  }
  return false;
}
 

Example 5

From project arquillian_deprecated, under directory /extensions/drone/src/main/java/org/jboss/arquillian/drone/impl/.

Source file: DroneRegistrar.java

  18 
vote

private static Class<?> getFirstGenericParameterType(Class<?> clazz,Class<?> rawType){
  for (  Type interfaceType : clazz.getGenericInterfaces()) {
    if (interfaceType instanceof ParameterizedType) {
      ParameterizedType ptype=(ParameterizedType)interfaceType;
      if (rawType.isAssignableFrom((Class<?>)ptype.getRawType())) {
        return (Class<?>)ptype.getActualTypeArguments()[0];
      }
    }
  }
  return null;
}
 

Example 6

From project capedwarf-green, under directory /connect/src/main/java/org/jboss/capedwarf/connect/server/.

Source file: ServerProxyHandler.java

  18 
vote

/** 
 * Get collection element type.
 * @param method the method
 * @return the element's type
 */
protected Class<?> elementType(Method method){
  Type rt=method.getGenericReturnType();
  if (rt instanceof ParameterizedType == false)   throw new IllegalArgumentException("Cannot get exact type: " + rt);
  ParameterizedType pt=(ParameterizedType)rt;
  Type[] ats=pt.getActualTypeArguments();
  if (ats == null || ats.length != 1 || (ats[0] instanceof Class == false))   throw new IllegalArgumentException("Illegal actual type: " + Arrays.toString(ats));
  return (Class)ats[0];
}
 

Example 7

From project cdi-arq-workshop, under directory /cdi/src/test/java/org/jboss/test/workshop/cdi/produces/support/.

Source file: BeanProducer.java

  18 
vote

@SuppressWarnings({"unchecked"}) @Produces public GenericQuery injectClass(InjectionPoint ip){
  Annotated annotated=ip.getAnnotated();
  Class clazz=Object.class;
  Type type=annotated.getBaseType();
  if (type instanceof ParameterizedType) {
    ParameterizedType pt=(ParameterizedType)type;
    clazz=(Class)pt.getActualTypeArguments()[0];
  }
  return new GenericQuery(clazz);
}
 

Example 8

From project Coffee-Framework, under directory /coffeeframework-core/src/main/java/coffee/util/.

Source file: Reflection.java

  18 
vote

/** 
 * @param field
 * @return
 */
public static Type[] extractGenericReturnTypeFor(Field field){
  if (field == null)   return new Type[]{};
  Type type=field.getGenericType();
  if (!(type instanceof ParameterizedType))   return new Type[]{};
  ParameterizedType ptype=(ParameterizedType)type;
  return ptype.getActualTypeArguments();
}
 

Example 9

From project commons-mom, under directory /src/main/java/com/zauberlabs/commons/mom/.

Source file: StructureType.java

  18 
vote

/** 
 * Answers the structure type of a property, given an instance and the property name, if it exists. Throws an exception otherwise The structure type is not the same that the property type. According to SLM format, it follows these rules: <ul> <li>If the given property is a simple or composite type in the target instance, its property type is returned</li> <li>Otherwise, if it is a composite type, the component type is returned</li> </ul>
 * @param target
 * @param propertyName
 * @return the property type
 */
@SuppressWarnings("rawtypes") public static Class<?> getStructureType(@NonNull final Object destination,@NotEmpty final String propertyName){
  Type targetType=getType(destination,propertyName);
  if (targetType instanceof Class) {
    return (Class)targetType;
  }
  if (targetType instanceof ParameterizedType) {
    ParameterizedType parameterizedType=(ParameterizedType)targetType;
    if (parameterizedType.getRawType() == List.class) {
      return (Class)parameterizedType.getActualTypeArguments()[0];
    }
  }
  return Ensure.that().fail("Unsupported type %s for propertyName %s in object %s",targetType,(Object)propertyName,destination);
}
 

Example 10

From project conversation, under directory /spi/src/main/java/org/jboss/seam/conversation/spi/.

Source file: SeamConversationContextFactory.java

  18 
vote

/** 
 * Produce matching Seam conversation context.
 * @param ip current injection point
 * @return new Seam conversation context instance
 */
@SuppressWarnings({"unchecked"}) @Produces public static SeamConversationContext produce(InjectionPoint ip){
  Annotated annotated=ip.getAnnotated();
  Class<?> storeType=null;
  if (annotated != null) {
    Type baseType=annotated.getBaseType();
    if (baseType instanceof ParameterizedType) {
      ParameterizedType pt=(ParameterizedType)baseType;
      storeType=(Class<?>)pt.getActualTypeArguments()[0];
    }
  }
  return getContext(storeType);
}
 

Example 11

From project core_1, under directory /api/src/main/java/org/switchyard/transform/.

Source file: BaseTransformer.java

  18 
vote

private Class<?> getType(Types type){
  try {
    ParameterizedType pt=(ParameterizedType)getClass().getGenericSuperclass();
    return (Class<?>)pt.getActualTypeArguments()[type.ordinal()];
  }
 catch (  Exception e) {
    return Object.class;
  }
}
 

Example 12

From project core_4, under directory /impl/src/main/java/org/richfaces/el/.

Source file: GenericsIntrospectionServiceImpl.java

  18 
vote

private Class<?> resolveType(Type type){
  Class<?> result=Object.class;
  if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType=(ParameterizedType)type;
    Type[] types=parameterizedType.getActualTypeArguments();
    if (types != null && types.length != 0) {
      Type actualType=types[0];
      if (actualType instanceof Class) {
        result=(Class<?>)actualType;
      }
    }
  }
  return result;
}
 

Example 13

From project datavalve, under directory /datavalve-core/src/main/java/org/fluttercode/datavalve/entity/.

Source file: AbstractEntityHome.java

  18 
vote

public Class<T> getEntityClass(){
  if (entityClass == null) {
    ParameterizedType parameterizedType=(ParameterizedType)getClass().getGenericSuperclass();
    Object value=parameterizedType.getActualTypeArguments()[0];
    if (value instanceof Class) {
      return (Class<T>)value;
    }
 else {
      throw new IllegalArgumentException("Unable to extract generic type information, please set manually using setEntityClass()");
    }
  }
  return entityClass;
}
 

Example 14

From project ddd-cqrs-sample, under directory /src/main/java/pl/com/bottega/cqrs/command/handler/spring/.

Source file: SpringHandlersProvider.java

  18 
vote

private ParameterizedType findByRawType(Type[] genericInterfaces,Class<?> expectedRawType){
  for (  Type type : genericInterfaces) {
    if (type instanceof ParameterizedType) {
      ParameterizedType parametrized=(ParameterizedType)type;
      if (expectedRawType.equals(parametrized.getRawType())) {
        return parametrized;
      }
    }
  }
  throw new RuntimeException();
}
 

Example 15

From project dozer, under directory /core/src/main/java/org/dozer/util/.

Source file: TypeResolver.java

  18 
vote

/** 
 * collects all TypeVariable -> Type mappings from the generic interfaces
 */
private static void collectActualTypeArguments(final Type[] genericInterfaces,final Map<TypeVariable<?>,Type> map){
  for (  Type genericInterface : genericInterfaces) {
    if (genericInterface instanceof ParameterizedType) {
      ParameterizedType parameterizedType=(ParameterizedType)genericInterface;
      collectActualTypeArguments(parameterizedType,map);
      Type rawType=parameterizedType.getRawType();
      collectActualTypeArguments(getGenericInterfaces(rawType),map);
    }
 else {
      collectActualTypeArguments(getGenericInterfaces(genericInterface),map);
    }
  }
}
 

Example 16

From project elasticsearch-osem, under directory /src/main/java/org/elasticsearch/osem/common/springframework/core/.

Source file: GenericTypeResolver.java

  18 
vote

private static void extractTypeVariablesFromGenericInterfaces(Type[] genericInterfaces,Map<TypeVariable,Type> typeVariableMap){
  for (  Type genericInterface : genericInterfaces) {
    if (genericInterface instanceof ParameterizedType) {
      ParameterizedType pt=(ParameterizedType)genericInterface;
      populateTypeMapFromParameterizedType(pt,typeVariableMap);
      if (pt.getRawType() instanceof Class) {
        extractTypeVariablesFromGenericInterfaces(((Class)pt.getRawType()).getGenericInterfaces(),typeVariableMap);
      }
    }
 else     if (genericInterface instanceof Class) {
      extractTypeVariablesFromGenericInterfaces(((Class)genericInterface).getGenericInterfaces(),typeVariableMap);
    }
  }
}
 

Example 17

From project enterprise, under directory /consistency-check/src/test/java/org/neo4j/consistency/report/.

Source file: ConsistencyReporterTest.java

  18 
vote

@Parameterized.Parameters public static List<Object[]> methods(){
  ArrayList<Object[]> methods=new ArrayList<Object[]>();
  for (  Method reporterMethod : ConsistencyReport.Reporter.class.getMethods()) {
    Type[] parameterTypes=reporterMethod.getGenericParameterTypes();
    ParameterizedType checkerParameter=(ParameterizedType)parameterTypes[parameterTypes.length - 1];
    Class reportType=(Class)checkerParameter.getActualTypeArguments()[1];
    for (    Method method : reportType.getMethods()) {
      if (!method.getName().equals("forReference")) {
        methods.add(new Object[]{reporterMethod,method});
      }
    }
  }
  return methods;
}
 

Example 18

From project fitnesse, under directory /src/fitnesse/slimTables/.

Source file: SlimTableTestSupport.java

  18 
vote

@SuppressWarnings("unchecked") private Class<T> getParameterizedClass(){
  Type superclass=this.getClass().getGenericSuperclass();
  if (superclass instanceof ParameterizedType) {
    ParameterizedType type=ParameterizedType.class.cast(superclass);
    return (Class<T>)type.getActualTypeArguments()[0];
  }
  throw new IllegalStateException("Unable to detect the actual type of SlimTable.");
}
 

Example 19

From project flatpack-java, under directory /core/src/main/java/com/getperka/flatpack/util/.

Source file: FlatPackTypes.java

  18 
vote

/** 
 * Recursively flatten a ParameterizedType into a list of simple types.
 */
public static List<Type> flatten(Type type){
  List<Type> toReturn=FlatPackCollections.listForAny();
  if (type instanceof ParameterizedType) {
    ParameterizedType param=(ParameterizedType)type;
    toReturn.add(erase(param.getRawType()));
    for (    Type arg : param.getActualTypeArguments()) {
      toReturn.addAll(flatten(arg));
    }
  }
 else {
    toReturn.add(type);
  }
  return toReturn;
}
 

Example 20

From project framework, under directory /impl/core/src/main/java/br/gov/frameworkdemoiselle/util/.

Source file: Reflections.java

  18 
vote

@SuppressWarnings("unchecked") public static <T>Class<T> getGenericTypeArgument(final Class<?> clazz,final int idx){
  final Type type=clazz.getGenericSuperclass();
  ParameterizedType paramType;
  try {
    paramType=(ParameterizedType)type;
  }
 catch (  ClassCastException cause) {
    paramType=(ParameterizedType)((Class<T>)type).getGenericSuperclass();
  }
  return (Class<T>)paramType.getActualTypeArguments()[idx];
}
 

Example 21

From project gatein-api-java, under directory /api/src/main/java/org/gatein/api/commons/.

Source file: PropertyType.java

  18 
vote

@SuppressWarnings("unchecked") public PropertyType(String name){
  this.name=name;
  final java.lang.reflect.Type genericSuperclass=getClass().getGenericSuperclass();
  if (genericSuperclass instanceof ParameterizedType) {
    ParameterizedType superclass=(ParameterizedType)genericSuperclass;
    valueType=(Class<T>)superclass.getActualTypeArguments()[0];
  }
 else {
    throw new IllegalArgumentException("Must instantiate Type with a specific Java type parameter");
  }
}
 

Example 22

From project google-gson, under directory /src/main/java/com/google/gson/internal/.

Source file: $Gson$Types.java

  18 
vote

/** 
 * Returns a two element array containing this map's key and value types in positions 0 and 1 respectively.
 */
public static Type[] getMapKeyAndValueTypes(Type context,Class<?> contextRawType){
  if (context == Properties.class) {
    return new Type[]{String.class,String.class};
  }
  Type mapType=getSupertype(context,contextRawType,Map.class);
  ParameterizedType mapParameterizedType=(ParameterizedType)mapType;
  return mapParameterizedType.getActualTypeArguments();
}
 

Example 23

From project gson, under directory /gson/src/main/java/com/google/gson/internal/.

Source file: $Gson$Types.java

  18 
vote

/** 
 * Returns a two element array containing this map's key and value types in positions 0 and 1 respectively.
 */
public static Type[] getMapKeyAndValueTypes(Type context,Class<?> contextRawType){
  if (context == Properties.class) {
    return new Type[]{String.class,String.class};
  }
  Type mapType=getSupertype(context,contextRawType,Map.class);
  ParameterizedType mapParameterizedType=(ParameterizedType)mapType;
  return mapParameterizedType.getActualTypeArguments();
}
 

Example 24

From project guice-jit-providers, under directory /core/src/com/google/inject/internal/.

Source file: InjectorImpl.java

  18 
vote

/** 
 * Converts a binding for a  {@code Key<TypeLiteral<T>>} to the value {@code TypeLiteral<T>}. It's a bit awkward because we have to pull out the inner type in the type literal.
 */
private <T>BindingImpl<TypeLiteral<T>> createTypeLiteralBinding(Key<TypeLiteral<T>> key,Errors errors) throws ErrorsException {
  Type typeLiteralType=key.getTypeLiteral().getType();
  if (!(typeLiteralType instanceof ParameterizedType)) {
    throw errors.cannotInjectRawTypeLiteral().toException();
  }
  ParameterizedType parameterizedType=(ParameterizedType)typeLiteralType;
  Type innerType=parameterizedType.getActualTypeArguments()[0];
  if (!(innerType instanceof Class) && !(innerType instanceof GenericArrayType) && !(innerType instanceof ParameterizedType)) {
    throw errors.cannotInjectTypeLiteralOf(innerType).toException();
  }
  @SuppressWarnings("unchecked") TypeLiteral<T> value=(TypeLiteral<T>)TypeLiteral.get(innerType);
  InternalFactory<TypeLiteral<T>> factory=new ConstantFactory<TypeLiteral<T>>(Initializables.of(value));
  return new InstanceBindingImpl<TypeLiteral<T>>(this,key,SourceProvider.UNKNOWN_SOURCE,factory,ImmutableSet.<InjectionPoint>of(),value);
}
 

Example 25

From project HBql, under directory /src/main/java/org/apache/hadoop/hbase/hbql/mapping/.

Source file: VersionAnnotationAttrib.java

  18 
vote

public VersionAnnotationAttrib(final String familyName,final String columnName,final Field field,final FieldType fieldType,final String getter,final String setter) throws HBqlException {
  super(familyName,columnName,field,fieldType,getter,setter);
  final ColumnVersionMap versionAnno=field.getAnnotation(ColumnVersionMap.class);
  final String annoname="@ColumnVersionMap annotation";
  if (!TypeSupport.isParentClass(Map.class,field.getType()))   throw new HBqlException(getObjectQualifiedName(field) + "has a " + annoname+ " so it "+ "must implement the Map interface");
  final ParameterizedType ptype=(ParameterizedType)field.getGenericType();
  final Type[] typeargs=ptype.getActualTypeArguments();
  final Type mapValueType=typeargs[1];
  this.defineAccessors();
}
 

Example 26

From project hibernate-commons-annotations, under directory /src/test/java/org/hibernate/annotations/common/test/reflection/java/generics/.

Source file: ApproximatingTypeEnvironmentTest.java

  18 
vote

public void testApproximatesGenericsAndWildcardsInCollectionsToTheirUpperBounds() throws Exception {
  Type type=BigBlob.class.getMethod("genericCollection",new Class[0]).getGenericReturnType();
  ParameterizedType approxType=(ParameterizedType)approximatingUnboundContext.bind(type);
  assertEquals(Map.class,approxType.getRawType());
  assertNull(approxType.getOwnerType());
  assertEquals(2,approxType.getActualTypeArguments().length);
  assertEquals(Object.class,approxType.getActualTypeArguments()[0]);
  assertEquals(Collection.class,approxType.getActualTypeArguments()[1]);
}
 

Example 27

From project hibernate-metamodelgen, under directory /src/test/java/org/hibernate/jpamodelgen/test/util/.

Source file: TestUtil.java

  18 
vote

public static void assertAttributeTypeInMetaModelFor(Class<?> clazz,String fieldName,Class<?> expectedType,String errorString){
  Field field=getFieldFromMetamodelFor(clazz,fieldName);
  assertNotNull(field,"Cannot find field '" + fieldName + "' in "+ clazz.getName());
  ParameterizedType type=(ParameterizedType)field.getGenericType();
  Type actualType=type.getActualTypeArguments()[1];
  if (expectedType.isArray()) {
    expectedType=expectedType.getComponentType();
    actualType=getComponentType(actualType);
  }
  assertEquals(actualType,expectedType,"Types do not match: " + buildErrorString(errorString,clazz));
}
 

Example 28

From project incubator-deltaspike, under directory /deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/.

Source file: HierarchyDiscovery.java

  18 
vote

private Type resolveType(Class<?> clazz){
  if (clazz.getTypeParameters().length > 0) {
    TypeVariable<?>[] actualTypeParameters=clazz.getTypeParameters();
    @SuppressWarnings("UnnecessaryLocalVariable") ParameterizedType parameterizedType=new ParameterizedTypeImpl(clazz,actualTypeParameters,clazz.getDeclaringClass());
    return parameterizedType;
  }
 else {
    return clazz;
  }
}
 

Example 29

From project airlift, under directory /event/src/main/java/io/airlift/event/client/.

Source file: TypeParameterUtils.java

  17 
vote

public static Type[] getTypeParameters(Class<?> desiredType,Type type){
  if (type instanceof Class) {
    Class<?> rawClass=(Class<?>)type;
    if (desiredType.equals(type)) {
      return null;
    }
    for (    Type iface : rawClass.getGenericInterfaces()) {
      Type[] collectionType=getTypeParameters(desiredType,iface);
      if (collectionType != null) {
        return collectionType;
      }
    }
    return getTypeParameters(desiredType,rawClass.getGenericSuperclass());
  }
  if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType=(ParameterizedType)type;
    Type rawType=parameterizedType.getRawType();
    if (desiredType.equals(rawType)) {
      return parameterizedType.getActualTypeArguments();
    }
    Type[] collectionTypes=getTypeParameters(desiredType,rawType);
    if (collectionTypes != null) {
      for (int i=0; i < collectionTypes.length; i++) {
        if (collectionTypes[i] instanceof TypeVariable) {
          TypeVariable<?> typeVariable=(TypeVariable<?>)collectionTypes[i];
          TypeVariable<?>[] rawTypeParams=((Class<?>)rawType).getTypeParameters();
          for (int j=0; j < rawTypeParams.length; j++) {
            if (typeVariable.getName().equals(rawTypeParams[j].getName())) {
              collectionTypes[i]=parameterizedType.getActualTypeArguments()[j];
            }
          }
        }
      }
    }
    return collectionTypes;
  }
  return null;
}
 

Example 30

From project Arecibo, under directory /util/src/main/java/com/ning/arecibo/util/lifecycle/.

Source file: LifecycledProvider.java

  17 
vote

/** 
 * This code is copied from Guice because they didn't have the foresite to make it public...
 * @param type look at the source of the Guice 1.0 TypeLiteral class
 * @return look at the source of the Guice 1.0 TypeLiteral class
 */
private static Class<?> getRawType(Type type){
  if (type instanceof Class<?>) {
    return (Class<?>)type;
  }
 else {
    if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType=(ParameterizedType)type;
      Type rawType=parameterizedType.getRawType();
      if (!(rawType instanceof Class<?>)) {
        throw new RuntimeException("Bad things");
      }
      return (Class<?>)rawType;
    }
    if (type instanceof GenericArrayType) {
      return Object[].class;
    }
    throw new RuntimeException("Bad things");
  }
}
 

Example 31

From project beanvalidation-tck, under directory /tests/src/main/java/org/hibernate/beanvalidation/tck/tests/bootstrap/.

Source file: ConfigurationTest.java

  17 
vote

@Test @SpecAssertion(section="4.4.3",id="a") public void testProviderUnderTestDefinesSubInterfaceOfConfiguration(){
  boolean foundSubinterfaceOfConfiguration=false;
  Type[] types=TestUtil.getValidationProviderUnderTest().getClass().getGenericInterfaces();
  for (  Type type : types) {
    if (type instanceof ParameterizedType) {
      ParameterizedType paramType=(ParameterizedType)type;
      Type[] typeArguments=paramType.getActualTypeArguments();
      for (      Type typeArgument : typeArguments) {
        if (typeArgument instanceof Class && Configuration.class.isAssignableFrom((Class)typeArgument)) {
          foundSubinterfaceOfConfiguration=true;
        }
      }
    }
  }
  assertTrue(foundSubinterfaceOfConfiguration,"Could not find subinterface of Configuration");
}
 

Example 32

From project Blitz, under directory /src/com/laxser/blitz/web/paramresolver/.

Source file: ResolverFactoryImpl.java

  17 
vote

private static Class<?>[] compileGenericParameterTypesDetail(Method method,int index){
  Type genericParameterType=method.getGenericParameterTypes()[index];
  ArrayList<Class<?>> typeDetailList=new ArrayList<Class<?>>();
  if (genericParameterType instanceof ParameterizedType) {
    ParameterizedType aType=(ParameterizedType)genericParameterType;
    Type[] parameterArgTypes=aType.getActualTypeArguments();
    for (    Type parameterArgType : parameterArgTypes) {
      if (parameterArgType instanceof Class) {
        typeDetailList.add((Class<?>)parameterArgType);
      }
 else {
        typeDetailList.add(String.class);
      }
    }
    Class<?>[] types=new Class[typeDetailList.size()];
    typeDetailList.toArray(types);
    return types;
  }
  return null;
}
 

Example 33

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.

Source file: GenericType.java

  17 
vote

static GenericType[] parametersOf(Type type){
  if (type instanceof Class) {
    Class clazz=(Class)type;
    if (clazz.isArray()) {
      GenericType t=new GenericType(clazz.getComponentType());
      if (t.size() > 0) {
        return new GenericType[]{t};
      }
 else {
        return EMPTY;
      }
    }
 else {
      return EMPTY;
    }
  }
  if (type instanceof ParameterizedType) {
    ParameterizedType pt=(ParameterizedType)type;
    Type[] parameters=pt.getActualTypeArguments();
    GenericType[] gts=new GenericType[parameters.length];
    for (int i=0; i < gts.length; i++) {
      gts[i]=new GenericType(parameters[i]);
    }
    return gts;
  }
  if (type instanceof GenericArrayType) {
    return new GenericType[]{new GenericType(((GenericArrayType)type).getGenericComponentType())};
  }
  if (type instanceof WildcardType) {
    return EMPTY;
  }
  if (type instanceof TypeVariable) {
    return EMPTY;
  }
  throw new IllegalStateException();
}
 

Example 34

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/templatecompiler/el/types/.

Source file: TypesFactoryImpl.java

  17 
vote

ELType createType(java.lang.reflect.Type reflectionType){
  java.lang.reflect.Type[] actualTypeArguments=null;
  Class<?> rawType=null;
  int arrayDepth=0;
  java.lang.reflect.Type localReflectionType=reflectionType;
  while (localReflectionType instanceof GenericArrayType) {
    localReflectionType=((GenericArrayType)localReflectionType).getGenericComponentType();
    arrayDepth++;
  }
  if (localReflectionType instanceof ParameterizedType) {
    ParameterizedType parameterizedType=(ParameterizedType)localReflectionType;
    actualTypeArguments=parameterizedType.getActualTypeArguments();
    rawType=(Class<?>)parameterizedType.getRawType();
  }
 else   if (localReflectionType instanceof Class<?>) {
    rawType=(Class<?>)localReflectionType;
  }
  if (rawType != null) {
    while (rawType.isArray()) {
      arrayDepth++;
      rawType=rawType.getComponentType();
    }
    ELType[] typeArguments=PlainClassType.NO_TYPES;
    if (!ArrayUtils.isEmpty(actualTypeArguments)) {
      typeArguments=getTypesArray(actualTypeArguments);
    }
    ELType clearComponentType=getPlainClassType(rawType);
    if (!ArrayUtils.isEmpty(typeArguments) || arrayDepth != 0) {
      return new ComplexType(clearComponentType,typeArguments,arrayDepth);
    }
 else {
      return clearComponentType;
    }
  }
 else {
    return getReferencedType(reflectionType.toString());
  }
}
 

Example 35

From project components-ness-jersey, under directory /jersey/src/main/java/com/nesscomputing/jersey/exceptions/.

Source file: GuiceProvisionExceptionMapper.java

  17 
vote

private Class<?> getType(Class<?> c){
  Class<?> _c=c;
  while (_c != Object.class) {
    Type[] ts=_c.getGenericInterfaces();
    for (    Type t : ts) {
      if (t instanceof ParameterizedType) {
        ParameterizedType pt=(ParameterizedType)t;
        if (pt.getRawType() == ExceptionMapper.class) {
          return getResolvedType(pt.getActualTypeArguments()[0],c,_c);
        }
      }
    }
    _c=_c.getSuperclass();
  }
  return null;
}
 

Example 36

From project Core_2, under directory /shell/src/main/java/org/jboss/forge/shell/project/resources/.

Source file: ResourceProducer.java

  17 
vote

@Produces @Current @SuppressWarnings({"rawtypes","unchecked"}) public Resource getCurrentResource(final InjectionPoint ip,final Shell shell){
  Resource<?> currentResource=shell.getCurrentResource();
  Type type=null;
  Member member=ip.getMember();
  if (member instanceof Field) {
    type=((Field)member).getType();
  }
 else   if (member instanceof Method) {
    AnnotatedParameter<?> annotated=(AnnotatedParameter<?>)ip.getAnnotated();
    type=annotated.getBaseType();
  }
 else   if (member instanceof Constructor<?>) {
    AnnotatedParameter<?> annotated=(AnnotatedParameter<?>)ip.getAnnotated();
    type=annotated.getBaseType();
  }
  try {
    Class<? extends Resource> resourceClass=currentResource.getClass();
    if ((type instanceof Class) && ((Class)type).isAssignableFrom(resourceClass)) {
      return currentResource;
    }
 else     if (type instanceof ParameterizedType) {
      ParameterizedType t=(ParameterizedType)type;
      Type rawType=t.getRawType();
      if ((rawType instanceof Class) && ((Class)rawType).isAssignableFrom(resourceClass)) {
        return currentResource;
      }
    }
  }
 catch (  Exception e) {
    throw new IllegalStateException("Could not @Inject Resource type into InjectionPoint:" + ip,e);
  }
  return null;
}
 

Example 37

From project DTRules, under directory /dtrules-engine/src/main/java/com/dtrules/automapping/access/.

Source file: JavaSource.java

  17 
vote

/** 
 * We look at the return type specified on the Method to determine the subType of a List.  For anything else, we are going to return a null for the subType.
 * @param method 
 * @return subType of list
 */
private Class<?> getSubType(Method method){
  Type returnType=method.getGenericReturnType();
  Class<?> returnClass=null;
  if (returnType instanceof ParameterizedType) {
    ParameterizedType type=(ParameterizedType)returnType;
    Type[] typeArguments=type.getActualTypeArguments();
    for (    Type typeArgument : typeArguments) {
      try {
        returnClass=(Class<?>)typeArgument;
      }
 catch (      Exception e) {
        returnClass=Class.class;
      }
    }
  }
  return returnClass;
}
 

Example 38

From project encog-java-workbench, under directory /src/main/java/org/encog/workbench/editor/.

Source file: ObjectEditorFrame.java

  17 
vote

private void performAdd(){
  try {
    TreePath path=this.tree.getSelectionPath();
    DefaultMutableTreeNode node=(DefaultMutableTreeNode)path.getLastPathComponent();
    if (!(node.getUserObject() instanceof String)) {
      node=(DefaultMutableTreeNode)node.getParent();
    }
    DefaultMutableTreeNode parent=(DefaultMutableTreeNode)node.getParent();
    Object obj=parent.getUserObject();
    String fieldName=node.getUserObject().toString();
    Field field=obj.getClass().getDeclaredField(fieldName);
    field.setAccessible(true);
    Object fieldObject=field.get(obj);
    if (fieldObject instanceof Collection) {
      ParameterizedType gtype=(ParameterizedType)field.getGenericType();
      java.lang.reflect.Type[] types=gtype.getActualTypeArguments();
      Object item=((Class)types[0]).newInstance();
      ((Collection)fieldObject).add(item);
      generateTree();
    }
  }
 catch (  SecurityException e) {
    throw new WorkBenchError(e);
  }
catch (  NoSuchFieldException e) {
    throw new WorkBenchError(e);
  }
catch (  IllegalAccessException e) {
    throw new WorkBenchError(e);
  }
catch (  InstantiationException e) {
    throw new WorkBenchError(e);
  }
}
 

Example 39

From project fastjson, under directory /src/main/java/com/alibaba/fastjson/parser/deserializer/.

Source file: MapDeserializer.java

  17 
vote

@SuppressWarnings({"rawtypes","unchecked"}) protected Object deserialze(DefaultJSONParser parser,Type type,Object fieldName,Map map){
  if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType=(ParameterizedType)type;
    Type keyType=parameterizedType.getActualTypeArguments()[0];
    Type valueType=parameterizedType.getActualTypeArguments()[1];
    if (String.class == keyType) {
      return DefaultObjectDeserializer.instance.parseMap(parser,(Map<String,Object>)map,valueType,fieldName);
    }
 else {
      return DefaultObjectDeserializer.instance.parseMap(parser,map,keyType,valueType,fieldName);
    }
  }
 else {
    return parser.parseObject(map,fieldName);
  }
}
 

Example 40

From project gatein-management, under directory /rest/src/main/java/org/gatein/management/rest/providers/.

Source file: ManagedComponentProvider.java

  17 
vote

@SuppressWarnings("unchecked") private Class<T> getType(Type genericType){
  if (genericType instanceof ParameterizedType) {
    ParameterizedType pt=(ParameterizedType)genericType;
    Type[] arguments=pt.getActualTypeArguments();
    if (arguments != null && arguments.length == 1) {
      Type arg=arguments[0];
      if (arg instanceof TypeVariable) {
        return (Class<T>)((TypeVariable)arg).getBounds()[0];
      }
 else {
        return (Class<T>)arg;
      }
    }
 else {
      return (Class<T>)pt.getRawType();
    }
  }
 else {
    return (Class<T>)genericType;
  }
}
 

Example 41

From project geronimo-xbean, under directory /xbean-reflect/src/main/java/org/apache/xbean/recipe/.

Source file: RecipeHelper.java

  17 
vote

public static Class toClass(Type type){
  if (type instanceof Class) {
    Class clazz=(Class)type;
    return clazz;
  }
 else   if (type instanceof GenericArrayType) {
    GenericArrayType arrayType=(GenericArrayType)type;
    Class componentType=toClass(arrayType.getGenericComponentType());
    return Array.newInstance(componentType,0).getClass();
  }
 else   if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType=(ParameterizedType)type;
    return toClass(parameterizedType.getRawType());
  }
 else {
    return Object.class;
  }
}
 

Example 42

From project giraph, under directory /src/main/java/org/apache/giraph/utils/.

Source file: ReflectionUtils.java

  17 
vote

/** 
 * Get the actual type arguments a child class has used to extend a generic base class.
 * @param < T > Type to evaluate.
 * @param baseClass the base class
 * @param childClass the child class
 * @return a list of the raw classes for the actual type arguments.
 */
public static <T>List<Class<?>> getTypeArguments(Class<T> baseClass,Class<? extends T> childClass){
  Map<Type,Type> resolvedTypes=new HashMap<Type,Type>();
  Type type=childClass;
  while (!getClass(type).equals(baseClass)) {
    if (type instanceof Class) {
      type=((Class<?>)type).getGenericSuperclass();
    }
 else {
      ParameterizedType parameterizedType=(ParameterizedType)type;
      Class<?> rawType=(Class<?>)parameterizedType.getRawType();
      Type[] actualTypeArguments=parameterizedType.getActualTypeArguments();
      TypeVariable<?>[] typeParameters=rawType.getTypeParameters();
      for (int i=0; i < actualTypeArguments.length; i++) {
        resolvedTypes.put(typeParameters[i],actualTypeArguments[i]);
      }
      if (!rawType.equals(baseClass)) {
        type=rawType.getGenericSuperclass();
      }
    }
  }
  Type[] actualTypeArguments;
  if (type instanceof Class) {
    actualTypeArguments=((Class<?>)type).getTypeParameters();
  }
 else {
    actualTypeArguments=((ParameterizedType)type).getActualTypeArguments();
  }
  List<Class<?>> typeArgumentsAsClasses=new ArrayList<Class<?>>();
  for (  Type baseType : actualTypeArguments) {
    while (resolvedTypes.containsKey(baseType)) {
      baseType=resolvedTypes.get(baseType);
    }
    typeArgumentsAsClasses.add(getClass(baseType));
  }
  return typeArgumentsAsClasses;
}
 

Example 43

From project Guit, under directory /src/main/java/com/guit/junit/dom/.

Source file: ElementsImplGenerator.java

  17 
vote

private static String print(Method m){
  StringBuilder sb=new StringBuilder();
  Type c=m.getGenericReturnType();
  if (c instanceof ParameterizedType) {
    ParameterizedType pt=(ParameterizedType)c;
    sb.append(((Class<?>)pt.getRawType()).getCanonicalName());
    sb.append("<");
    boolean f=true;
    for (    Type t : pt.getActualTypeArguments()) {
      if (f) {
        f=false;
      }
 else {
        sb.append(", ");
      }
      sb.append(((Class<?>)t).getCanonicalName());
    }
    sb.append(">");
  }
 else {
    sb.append(m.getReturnType().getCanonicalName());
  }
  return sb.toString();
}
 

Example 44

From project hibernate-validator, under directory /engine/src/main/java/org/hibernate/validator/internal/util/.

Source file: ReflectionHelper.java

  17 
vote

/** 
 * Determines the type of elements of an <code>Iterable</code>, array or the value of a <code>Map</code>.
 * @param type the type to inspect
 * @return Returns the type of elements of an <code>Iterable</code>, array or the value of a <code>Map</code>. <code>null</code> is returned in case the type is not indexable (in the context of JSR 303).
 */
public static Type getIndexedType(Type type){
  Type indexedType=null;
  if (isIterable(type) && type instanceof ParameterizedType) {
    ParameterizedType paramType=(ParameterizedType)type;
    indexedType=paramType.getActualTypeArguments()[0];
  }
 else   if (isMap(type) && type instanceof ParameterizedType) {
    ParameterizedType paramType=(ParameterizedType)type;
    indexedType=paramType.getActualTypeArguments()[1];
  }
 else   if (TypeHelper.isArray(type)) {
    indexedType=TypeHelper.getComponentType(type);
  }
  return indexedType;
}
 

Example 45

From project aerogear-controller, under directory /src/main/java/org/jboss/aerogear/controller/util/.

Source file: TypeNameExtractor.java

  15 
vote

public String nameFor(Type generic){
  if (generic instanceof ParameterizedType) {
    return nameFor((ParameterizedType)generic);
  }
  if (generic instanceof WildcardType) {
    return nameFor((WildcardType)generic);
  }
  if (generic instanceof TypeVariable<?>) {
    return nameFor(((TypeVariable<?>)generic));
  }
  return nameFor((Class<?>)generic);
}
 

Example 46

From project alljoyn_java, under directory /src/org/alljoyn/bus/.

Source file: Signature.java

  15 
vote

/** 
 * Compute the DBus type signature of the type.
 * @param type the Java type
 * @param signature the annotated signature for the type
 * @return the DBus type signature
 * @throws AnnotationBusException if the signature cannot be computed
 */
public static String typeSig(Type type,String signature) throws AnnotationBusException {
  if (type instanceof ParameterizedType) {
    return parameterizedTypeSig((ParameterizedType)type,signature);
  }
 else   if (type instanceof Class) {
    return classTypeSig((Class)type,signature);
  }
 else   if (type instanceof GenericArrayType) {
    return genericArrayTypeSig((GenericArrayType)type,signature);
  }
 else {
    throw new AnnotationBusException("cannot determine signature for " + type);
  }
}
 

Example 47

From project beanstalker, under directory /beanstalker-common/src/main/java/br/com/ingenieux/mojo/aws/util/.

Source file: TypeUtil.java

  15 
vote

public static Class<?> getServiceClass(Class<?> c){
  Class<?> prevClass=c;
  while (0 == c.getTypeParameters().length) {
    prevClass=c;
    c=c.getSuperclass();
  }
  return (Class<?>)((ParameterizedType)prevClass.getGenericSuperclass()).getActualTypeArguments()[0];
}
 

Example 48

From project Collections, under directory /src/main/java/vanilla/java/collections/impl/.

Source file: HugeCollectionBuilder.java

  15 
vote

protected HugeCollectionBuilder(int typeParameter){
  type=(Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[typeParameter];
  typeModel=new TypeModel<T>(type);
  classLoader=getClass().getClassLoader();
  try {
    @SuppressWarnings({"UnusedDeclaration"}) Class classWriter=ClassWriter.class;
    disableCodeGeneration=false;
  }
 catch (  NoClassDefFoundError ignored) {
    disableCodeGeneration=true;
  }
}
 

Example 49

From project commons-j, under directory /src/main/java/nerds/antelax/commons/xml/saxbp/.

Source file: ParseInterest.java

  15 
vote

private static Class<?> checkAndGetJaxbClass(final Method method) throws SAXBPException {
  final Class<?>[] methodArgTypes=method.getParameterTypes();
  if (methodArgTypes.length != 1 || !JAXBElement.class.getName().equals(methodArgTypes[0].getName()))   throw new SAXBPException("JAXB handler method must take a single argument of type JAXBElement<...>");
  final Type jaxbType=((ParameterizedType)method.getGenericParameterTypes()[0]).getActualTypeArguments()[0];
  if (!(jaxbType instanceof Class<?>))   throw new SAXBPException("JAXB handler method must take a single argument of type JAXBElement<...>");
  return (Class<?>)jaxbType;
}
 

Example 50

From project droidparts, under directory /base/src/org/droidparts/reflect/util/.

Source file: ReflectionUtils.java

  15 
vote

public static Class<?>[] getFieldGenericArgs(Field field){
  Type genericType=field.getGenericType();
  if (genericType instanceof ParameterizedType) {
    Type[] typeArr=((ParameterizedType)genericType).getActualTypeArguments();
    Class<?>[] argsArr=new Class<?>[typeArr.length];
    for (int i=0; i < typeArr.length; i++) {
      String[] nameParts=typeArr[i].toString().split(" ");
      String clsName=nameParts[nameParts.length - 1];
      argsArr[i]=classForName(clsName);
    }
    return argsArr;
  }
 else {
    return new Class<?>[0];
  }
}
 

Example 51

From project eclipse.platform.runtime, under directory /bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/.

Source file: ContextObjectSupplier.java

  15 
vote

private String typeToString(Type type){
  if (type == null)   return null;
  if (type instanceof Class<?>)   return ((Class<?>)type).getName();
  if (type instanceof ParameterizedType) {
    Type rawType=((ParameterizedType)type).getRawType();
    return typeToString(rawType);
  }
  return null;
}
 

Example 52

From project eucalyptus, under directory /clc/modules/axis2-transport/src/edu/ucsb/eucalyptus/transport/query/.

Source file: StorageQueryBinding.java

  15 
vote

private List<String> populateObjectList(final GroovyObject obj,final Map.Entry<String,String> paramFieldPair,final Map<String,String> params,final int paramSize){
  List<String> failedMappings=new ArrayList<String>();
  try {
    Field declaredField=obj.getClass().getDeclaredField(paramFieldPair.getValue());
    ArrayList theList=(ArrayList)obj.getProperty(paramFieldPair.getValue());
    Class genericType=(Class)((ParameterizedType)declaredField.getGenericType()).getActualTypeArguments()[0];
    if (String.class.equals(genericType)) {
      if (params.containsKey(paramFieldPair.getKey()))       theList.add(params.remove(paramFieldPair.getKey()));
 else       for (int i=0; i < paramSize + 1; i++)       if (params.containsKey(paramFieldPair.getKey() + "." + i))       theList.add(params.remove(paramFieldPair.getKey() + "." + i));
    }
 else     if (declaredField.isAnnotationPresent(HttpEmbedded.class)) {
      HttpEmbedded annoteEmbedded=(HttpEmbedded)declaredField.getAnnotation(HttpEmbedded.class);
      if (annoteEmbedded.multiple()) {
        String prefix=paramFieldPair.getKey();
        List<String> embeddedListFieldNames=new ArrayList<String>();
        for (        String actualParameterName : params.keySet())         if (actualParameterName.matches(prefix + ".1.*"))         embeddedListFieldNames.add(actualParameterName.replaceAll(prefix + ".1.",""));
        for (int i=0; i < paramSize + 1; i++) {
          boolean foundAll=true;
          Map<String,String> embeddedParams=new HashMap<String,String>();
          for (          String fieldName : embeddedListFieldNames) {
            String paramName=prefix + "." + i+ "."+ fieldName;
            if (!params.containsKey(paramName)) {
              failedMappings.add("Mismatched embedded field: " + paramName);
              foundAll=false;
            }
 else             embeddedParams.put(fieldName,params.get(paramName));
          }
          if (foundAll)           failedMappings.addAll(populateEmbedded(genericType,embeddedParams,theList));
 else           break;
        }
      }
 else       failedMappings.addAll(populateEmbedded(genericType,params,theList));
    }
  }
 catch (  Exception e1) {
    failedMappings.add(paramFieldPair.getKey());
  }
  return failedMappings;
}
 

Example 53

From project fairy, under directory /fairy-core/src/main/java/com/mewmew/fairy/v1/cli/.

Source file: StringParsers.java

  15 
vote

public StringParsers addParser(StringParser t){
  Type type=t.getClass().getGenericInterfaces()[0];
  if (type instanceof ParameterizedType) {
    parsers.put((Class)((ParameterizedType)type).getActualTypeArguments()[0],t);
  }
  return this;
}
 

Example 54

From project fest-reflect, under directory /src/main/java/org/fest/reflect/reference/.

Source file: TypeRef.java

  15 
vote

/** 
 * Creates a new </code> {@link TypeRef}</code>.
 * @throws ReflectionError if the generic type of this reference is missing type parameter.
 */
public TypeRef(){
  Type superclass=getClass().getGenericSuperclass();
  if (superclass instanceof Class<?>)   throw new ReflectionError("Missing type parameter.");
  Type type=((ParameterizedType)superclass).getActualTypeArguments()[0];
  rawType=type instanceof Class<?> ? (Class<?>)type : (Class<?>)((ParameterizedType)type).getRawType();
}
 

Example 55

From project Gemini-Blueprint, under directory /core/src/main/java/org/eclipse/gemini/blueprint/blueprint/container/.

Source file: TypeFactory.java

  15 
vote

private static ReifiedType getReifiedType(Type targetType){
  if (targetType instanceof Class) {
    if (Object.class.equals(targetType)) {
      return OBJECT;
    }
    return new GenericsReifiedType((Class<?>)targetType);
  }
  if (targetType instanceof ParameterizedType) {
    Type ata=((ParameterizedType)targetType).getActualTypeArguments()[0];
    return getReifiedType(ata);
  }
  if (targetType instanceof WildcardType) {
    WildcardType wt=(WildcardType)targetType;
    Type[] lowerBounds=wt.getLowerBounds();
    if (ObjectUtils.isEmpty(lowerBounds)) {
      Type upperBound=wt.getUpperBounds()[0];
      return getReifiedType(upperBound);
    }
    return getReifiedType(lowerBounds[0]);
  }
  if (targetType instanceof TypeVariable) {
    Type[] bounds=((TypeVariable<?>)targetType).getBounds();
    return getReifiedType(bounds[0]);
  }
  if (targetType instanceof GenericArrayType) {
    return getReifiedType(((GenericArrayType)targetType).getGenericComponentType());
  }
  throw new IllegalArgumentException("Unknown type " + targetType.getClass());
}
 

Example 56

From project grails-data-mapping, under directory /grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/engine/internal/.

Source file: MappingUtils.java

  15 
vote

public static Class getGenericTypeForProperty(Class javaClass,String propertyName){
  Class genericClass=null;
  try {
    Field declaredField=javaClass.getDeclaredField(propertyName);
    Type genericType=declaredField.getGenericType();
    if (genericType instanceof ParameterizedType) {
      Type[] typeArguments=((ParameterizedType)genericType).getActualTypeArguments();
      if (typeArguments.length > 0) {
        genericClass=(Class)typeArguments[0];
      }
    }
  }
 catch (  NoSuchFieldException e) {
  }
  return genericClass;
}
 

Example 57

From project grails-searchable, under directory /src/java/grails/plugin/searchable/internal/.

Source file: SearchableUtils.java

  15 
vote

/** 
 * If the given domain class property is a generic collection, this method returns the element type of that collection. Otherwise, it returns <code>null</code>.
 */
public static Class getElementClass(GrailsDomainClassProperty property){
  PropertyDescriptor descriptor=BeanUtils.getPropertyDescriptor(property.getDomainClass().getClazz(),property.getName());
  Type type=descriptor.getReadMethod().getGenericReturnType();
  if (type instanceof ParameterizedType) {
    for (    Type argType : ((ParameterizedType)type).getActualTypeArguments()) {
      return (Class)argType;
    }
  }
  return null;
}