Java Code Examples for org.apache.commons.lang3.reflect.TypeUtils#isAssignable()

The following examples show how to use org.apache.commons.lang3.reflect.TypeUtils#isAssignable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeCoercerImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isSupportedType(Class<?> clazz, Type type) {
   if (type == null) {
      return false;
   }
   if (TypeUtils.isAssignable(type, clazz)) {
      return true;
   }
   TypeHandler<?> handler = getHandler(clazz);
   if (handler != null) {
      return handler.isSupportedType(type);
   }
   if (clazz.isEnum()) {
      return enumHandler.isSupportedType(clazz, type);
   }
   return false;
}
 
Example 2
Source File: ExceptionMapperRegistryBuilder.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
private Class<? extends Throwable> getGenericType(Class<? extends JsonApiExceptionMapper> mapper) {
  Type[] types = mapper.getGenericInterfaces();
  if (null == types || 0 == types.length ){
    types = new Type[]{mapper.getGenericSuperclass()};
  }

  for (Type type : types) {
    if (type instanceof ParameterizedType && (TypeUtils.isAssignable(((ParameterizedType) type).getRawType(),JsonApiExceptionMapper.class)
        || TypeUtils.isAssignable(((ParameterizedType) type).getRawType(),ExceptionMapper.class))) {
      //noinspection unchecked
      return (Class<? extends Throwable>) ((ParameterizedType) type).getActualTypeArguments()[0];
    }
  }
  //Won't get in here
  return null;
}
 
Example 3
Source File: PairingDeviceResolver.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Function<? super PlatformMessage, ?> getResolverForParameter(Method method, Type parameter, Annotation[] annotations) {
	if(PairingDevice.class.equals(parameter)) {
		return this::findPairingDevice;
	}
	if(PersistentModelWrapper.class.equals(TypeUtils.getRawType(parameter, null)) && TypeUtils.isAssignable(PairingDeviceWrapper, parameter)) {
		return this::findPairingDeviceWrapper;
	}
	return null;
}
 
Example 4
Source File: TypeHandlerImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isSupportedType(Type type) {
   if (type == null) {
      return false;
   }
   if (TypeUtils.isAssignable(type, targetType)) {
      return true;
   }
   for (Class<?> clazz : supportedTypes) {
      if (TypeUtils.isAssignable(type, clazz)) {
         return true;
      }
   }
   return false;
}
 
Example 5
Source File: TracepointsTestUtils.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static MethodTracepointSpec getMethodSpec(Class<?> cls, String methodName)
        throws ClassNotFoundException {
    MethodTracepointSpec.Builder b = MethodTracepointSpec.newBuilder();
    b.setClassName(cls.getName());
    b.setMethodName(methodName);

    Method m = getMethod(cls, methodName);
    for (Class<?> paramClass : m.getParameterTypes()) {
        b.addParamClass(paramClass.getCanonicalName());
    }

    int paramCount = 0;
    for (Type paramType : m.getGenericParameterTypes()) {
        String paramName = String.format("$%d", ++paramCount);
        if (TypeUtils.isArrayType(paramType)) {
            Type arrayOfType = TypeUtils.getArrayComponentType(paramType);
            String arrayOf = TypeUtils.toString(arrayOfType);
            b.addAdviceArgBuilder().getMultiBuilder().setLiteral(paramName).setPostProcess("{}")
                    .setType(arrayOf);
        } else if (TypeUtils.isAssignable(paramType, Collection.class)) {
            ParameterizedType pt = (ParameterizedType) paramType;
            Type collectionOfType = pt.getActualTypeArguments()[0]; // doesn't work if multiple type params, but
                                                                    // good enough
            String collectionOf = TypeUtils.toString(collectionOfType);
            b.addAdviceArgBuilder().getMultiBuilder().setLiteral(paramName).setPostProcess("{}")
                    .setType(collectionOf);
        } else {
            b.addAdviceArgBuilder().setLiteral(paramName);
        }
    }

    return b.build();
}
 
Example 6
Source File: Tracepoints.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Create a tracepoint for the entry of the named method of the class.
 * The name of the tracepoint will be the short class name and the method name,
 * eg java.lang.String.format will have short name String.format
 * Parameter types will be looked up, and if the method is overloaded, returns one of the methods.
 * If any of the method arguments are arrays or collections, they will be exported as multi-variables
 */
public static MethodTracepoint create(Class<?> cls, String methodName, String... namesForMethodParameters) {
    Where where = Where.ENTRY;
    String tracepointName = String.format("%s.%s", cls.getSimpleName(), methodName);
    
    // Find the method
    Method m = getMethod(cls, methodName, namesForMethodParameters.length);
    
    // Create the tracepoint
    MethodTracepoint tracepoint = new MethodTracepoint(tracepointName, where, m);
    
    // Export the arguments as variables
    int paramCount = 0;
    for (Type paramType : m.getGenericParameterTypes()) {
        String exportAs = namesForMethodParameters[paramCount];
        String literal = String.format("$%d", ++paramCount);
        if (TypeUtils.isArrayType(paramType)) {
            Type arrayOfType = TypeUtils.getArrayComponentType(paramType);
            String arrayOf = TypeUtils.toString(arrayOfType);
            tracepoint.addMultiExport(exportAs, literal, arrayOf);
        } else if (TypeUtils.isAssignable(paramType, Collection.class)) {
            ParameterizedType pt = (ParameterizedType) paramType;
            Type collectionOfType = pt.getActualTypeArguments()[0];
            String collectionOf = TypeUtils.toString(collectionOfType);
            tracepoint.addMultiExport(exportAs, literal, collectionOf);
        } else {
            tracepoint.addExport(exportAs, literal);
        }
    }
    
    return tracepoint;
}
 
Example 7
Source File: PlatformDispatcherFactory.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public Function<? super PlatformMessage, ?> getResolverForParameter(Method method, Type parameter, Annotation[] annotations) {
   if(PlatformMessage.class.equals(parameter)) {
      return (message) -> message;
   }
   else if(Place.class.equals(parameter)) {
      return 
            (message) -> 
               !StringUtils.isEmpty(message.getPlaceId()) ? 
                  ServiceLocator.getInstance(PlaceDAO.class).findById(UUID.fromString(message.getPlaceId())) :
                  null ;
   }
   else if(MessageBody.class.equals(parameter)) {
      return (message) -> message.getValue();
   }
   if(definition != null) {
      for(Annotation annotation: annotations) {
         String name = null;
         if(annotation instanceof javax.inject.Named) {
            name = ((javax.inject.Named) annotation).value();
         }
         else if(annotation instanceof com.google.inject.name.Named) {
            name = ((com.google.inject.name.Named) annotation).value();
         }
         if(name != null) {
            for(ParameterDefinition arg: definition.getParameters()) {
               if(arg.getName().equals(name)) {
                  if(TypeUtils.isAssignable(arg.getType().getJavaType(), parameter)) {
                     return coerceFn(arg);
                  }
                  else {
                     throw new IllegalArgumentException("Argument " + name + " on method " + definition.getName() + " of type " + arg.getType() + " is not assignable to " + parameter + " (expected " + arg.getType().getJavaType() + ")");
                  }
               }
            }
            throw new IllegalArgumentException("Method " + definition.getName() + " does not support a parameter named " + name);
         }
      }
   }
   
   return null;
}
 
Example 8
Source File: PlatformDispatcherFactory.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public Function<? super PlatformMessage, ?> getResolverForParameter(Method method, Type parameter, Annotation[] annotations) {
   if(PlatformMessage.class.equals(parameter)) {
      return (message) -> message;
   }
   else if(Place.class.equals(parameter)) {
      return
            (message) ->
                  !StringUtils.isEmpty(message.getPlaceId()) ?
                        ServiceLocator.getInstance(PlaceDAO.class).findById(UUID.fromString(message.getPlaceId())) :
                        null ;
   }
   else if(MessageBody.class.equals(parameter)) {
      return (message) -> message.getValue();
   }
   if(definition != null) {
      for(Annotation annotation: annotations) {
         String name = null;
         if(annotation instanceof javax.inject.Named) {
            name = ((javax.inject.Named) annotation).value();
         }
         else if(annotation instanceof com.google.inject.name.Named) {
            name = ((com.google.inject.name.Named) annotation).value();
         }
         if(name != null) {
            for(ParameterDefinition arg: definition.getParameters()) {
               if(arg.getName().equals(name)) {
                  if(TypeUtils.isAssignable(arg.getType().getJavaType(), parameter)) {
                     return coerceFn(arg);
                  }
                  else {
                     throw new IllegalStateException("Argument " + name + " on event " + definition.getName() + " of type " + arg.getType() + " is not assignable to " + parameter + " (expected " + arg.getType().getJavaType() + ")");
                  }
               }
            }
            throw new IllegalStateException("Event " + definition.getName() + " does not support a parameter named " + name);
         }
      }
   }

   return null;
}
 
Example 9
Source File: UnsupportedTypePredicate.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public boolean apply(Type input) {
   return input != null ? TypeUtils.isAssignable(input, clazz) : false;
}
 
Example 10
Source File: EnumHandler.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public boolean isSupportedType(Class<?> clazz, Type type) {
   if (type == null) {
      return false;
   }
   return TypeUtils.isAssignable(type, clazz) || String.class.equals(type);
}
 
Example 11
Source File: IntrospectionUtils.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Determines whether a type represented by a class object is
 * convertible to another type represented by a class object using a
 * method invocation conversion, without matching object and primitive
 * types. This method is used to determine the more specific type when
 * comparing signatures of methods.
 *
 * @param formal the formal parameter type to which the actual
 * parameter type should be convertible
 * @param actual the actual parameter type.
 * @param possibleVarArg whether or not we're dealing with the last parameter
 * in the method declaration
 * @return true if either formal type is assignable from actual type,
 * or formal and actual are both primitive types and actual can be
 * subject to widening conversion to formal.
 */
public static boolean isStrictMethodInvocationConvertible(Type formal,
                                                          Class actual,
                                                          boolean possibleVarArg)
{
    Class formalClass = getTypeClass(formal);
    if (formalClass != null)
    {
        /* Check for nullity */
        if (actual == null)
        {
            return !formalClass.isPrimitive();
        }

        /* Check for identity or widening reference conversion */
        if (formalClass.isAssignableFrom(actual))
        {
            return true;
        }

        /* Check for widening primitive conversion. */
        if (formalClass.isPrimitive())
        {
            if (formal == Short.TYPE && (actual == Byte.TYPE))
                return true;
            if (formal == Integer.TYPE &&
                (actual == Short.TYPE || actual == Byte.TYPE))
                return true;
            if (formal == Long.TYPE &&
                (actual == Integer.TYPE || actual == Short.TYPE ||
                    actual == Byte.TYPE))
                return true;
            if (formal == Float.TYPE &&
                (actual == Long.TYPE || actual == Integer.TYPE ||
                    actual == Short.TYPE || actual == Byte.TYPE))
                return true;
            if (formal == Double.TYPE &&
                (actual == Float.TYPE || actual == Long.TYPE ||
                    actual == Integer.TYPE || actual == Short.TYPE ||
                    actual == Byte.TYPE))
                return true;
        }

        /* Check for vararg conversion. */
        if (possibleVarArg && formalClass.isArray())
        {
            if (actual.isArray())
            {
                actual = actual.getComponentType();
            }
            return isStrictMethodInvocationConvertible(formalClass.getComponentType(),
                actual, false);
        }
        return false;
    }
    else
    {
        // no distinction between strict and implicit, not a big deal in this case
        if (TypeUtils.isAssignable(actual, formal))
        {
            return true;
        }
        return possibleVarArg && TypeUtils.isArrayType(formal) &&
            TypeUtils.isAssignable(actual, TypeUtils.getArrayComponentType(formal));
    }
}