下面列出了org.apache.commons.lang3.ClassUtils#isAssignable ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@ReadOperation
public Map<String, Object> invoke() {
Map<String, Object> result = new HashMap<>(8);
if (!(ClassUtils.isAssignable(applicationContext.getEnvironment().getClass(),
ConfigurableEnvironment.class))) {
result.put("error", "environment type not match ConfigurableEnvironment: "
+ applicationContext.getEnvironment().getClass().getName());
}
else {
result.put("nacosConfigMetadata", nacosConfigMetadataMap.values());
result.put("nacosConfigGlobalProperties",
PropertiesUtils.extractSafeProperties(applicationContext.getBean(
CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME, Properties.class)));
}
return result;
}
private static int getConversionScore(Class<?> from, Class<?> to) {
if (from.equals(to)) {
return Integer.MAX_VALUE;
} else if (ClassUtils.isAssignable(from, to)) {
return Integer.MAX_VALUE - 1;
} else if (String.class.equals(to)) {
return Integer.MAX_VALUE - 2;
} else if (ClassUtils.isPrimitiveOrWrapper(to) && String.class.isAssignableFrom(from)) {
return Integer.MAX_VALUE - 3 - primitiveOrder.indexOf(to);
}
List<Class<?>> ordered = buildOrderedListForType(to);
if (ordered.contains(from)) {
return Integer.MAX_VALUE - 100 - ordered.indexOf(from);
}
int ind = 0;
for (Class<?> conv : ordered) {
++ind;
if (isConvertible(conv, to)) {
return Integer.MAX_VALUE - 200 - ind;
}
}
return Integer.MIN_VALUE;
}
/**
* Calls all functions defined under Functions in order.
*
* @param rs
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public Object invokeFunctionChain(ResultSet rs)
throws SQLException,
IllegalAccessException,
InvocationTargetException,
InstantiationException {
Object startingValue = null;
Class<?> argType = getResolvedPlan().getDynamicArgumentType();
if (argType != null && ClassUtils.isAssignable(ResultSet.class, argType)) {
startingValue = rs;
} else {
startingValue = rs.getObject(name, type);
}
return ConvertUtils.convert(getResolvedPlan().invoke(startingValue), type);
}
/**
* Converts the passed value to the passed type if possible.
*
* Conversion is performed in the following order:
* - Returned as-is if the value is of the same type or a sub-class of the
* type.
* - If type is java.lang.String, call toString on value and return it.
* - If value is a primitive, primitive wrapper, or String, and type
* represents one of those as well, an attempt is made to convert from/to
* as needed.
* - Otherwise, look for a constructor in the passed type that accepts a
* single argument of:
* o value itself (as its type or an interface/superclass)
* o A String argument, in which case toString is called on value
* o If value is primitive, the primitive type or it's wrapper
* o If value is a String, a primitive or wrapper argument
*
* @param value
* @param type
* @return
*/
public static Object convert(Object value, Class<?> type)
throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
if (ClassUtils.isAssignable(value.getClass(), type)) {
return value;
} else if (String.class.equals(type)) {
return value.toString();
} else if (ClassUtils.isPrimitiveOrWrapper(type) && value instanceof String) {
return ConvertUtils.convert(value, type);
}
Constructor<?> constr = getConvertibleConstructor(value.getClass(), type);
Class<?> pt = (constr != null && constr.getParameterCount() > 0) ? constr.getParameterTypes()[0] : null;
if (!ClassUtils.isAssignable(value.getClass(), pt)) {
if (pt != null && ClassUtils.isAssignable(String.class, pt)) {
return constr.newInstance(value.toString());
} else if (pt != null && ClassUtils.isPrimitiveOrWrapper(pt) && value instanceof String) {
return constr.newInstance(ConvertUtils.convert(value, pt));
}
// try anyway...
}
return constr.newInstance(value);
}
/**
* Gets the number of steps required needed to turn the source class into
* the destination class. This represents the number of steps in the object
* hierarchy graph.
*
* @param srcClass The source class
* @param destClass The destination class
* @return The cost of transforming an object
*/
private static float getObjectTransformationCost(Class<?> srcClass, final Class<?> destClass) {
if (destClass.isPrimitive()) {
return getPrimitivePromotionCost(srcClass, destClass);
}
float cost = 0.0f;
while (srcClass != null && !destClass.equals(srcClass)) {
if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) {
// slight penalty for interface match.
// we still want an exact match to override an interface match,
// but
// an interface match should override anything where we have to
// get a superclass.
cost += 0.25f;
break;
}
cost++;
srcClass = srcClass.getSuperclass();
}
/*
* If the destination class is null, we've travelled all the way up to
* an Object match. We'll penalize this by adding 1.5 to the cost.
*/
if (srcClass == null) {
cost += 1.5f;
}
return cost;
}
private void validateArgumentsCompatibility(String call, Class<?>[] parameterTypes, List<Argument> arguments, boolean strictCheck) {
if (parameterTypes.length != arguments.size()) {
throw new IllegalStateException(String.format(INCOMPATIBLE_ARGUMENTS, call, toString(parameterTypes), toString(arguments)));
}
for (int i = 0, len = parameterTypes.length; i < len; i++) {
Class<?> type = parameterTypes[i];
Argument argument = arguments.get(i);
if (!ClassUtils.isAssignable(extractClass(argument.getType()), type)
&& (strictCheck || !UNKNOWN.equals(argument.getType()))) {
throw new IllegalStateException(String.format(INCOMPATIBLE_ARGUMENTS, call, toString(parameterTypes), toString(arguments)));
}
}
}
public AbstractCaller() {
try {
Method[] classMethods = getClass().getMethods();
for(Method classMethod : classMethods) {
if(classMethod.isAnnotationPresent(ActionMethod.class)) {
Class<?>[] types = classMethod.getParameterTypes();
if(ClassUtils.isAssignable(types, IActionContext.class)) {
withSettings.put(classMethod.getName(), classMethod);
} else if(ClassUtils.isAssignable(types, IActionContext.class, IMessage.class)) {
withIMessage.put(classMethod.getName(), classMethod);
} else if(ClassUtils.isAssignable(types, IActionContext.class, BaseMessage.class)) {
withBaseMessage.put(classMethod.getName(), classMethod);
} else if(ClassUtils.isAssignable(types, IActionContext.class, HashMap.class)) {
withHashMap.put(classMethod.getName(), classMethod);
} else if(ClassUtils.isAssignable(types, IActionContext.class, Object.class)) {
withObject.put(classMethod.getName(), classMethod);
} else {
throw new ActionManagerException("Unknown action method signature: " + getSignature(classMethod.getName(), types));
}
} else if(classMethod.isAnnotationPresent(UtilityMethod.class)) {
utilityMethods.put(classMethod.getName(), classMethod);
}
}
} catch(Exception e) {
throw new EPSCommonException(e);
}
}
private <T> T call(String actionName, Multimap<String, Method> methodMap, Object... args) throws InterruptedException {
Collection<Method> actionMethods = methodMap.get(actionName);
Class<?>[] argTypes = ClassUtils.toClass(args);
for(Method actionMethod : actionMethods) {
if(ClassUtils.isAssignable(argTypes, actionMethod.getParameterTypes())) {
return call(actionMethod, args);
}
}
throw new ActionNotFoundException(getSignature(actionName, args));
}
private boolean isPrimitiveType(Type type) {
if (type instanceof Class) {
Class clazz = (Class) type;
if (ClassUtils.isPrimitiveOrWrapper(clazz) || ClassUtils
.isAssignable(clazz, String.class)) {
return true;
}
}
return false;
}
/**
* <p>Find an accessible method that matches the given name and has compatible parameters.
* Compatible parameters mean that every method parameter is assignable from
* the given parameters.
* In other words, it finds a method with the given name
* that will take the parameters given.<p>
*
* <p>This method is used by
* {@link
* #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}.
*
* <p>This method can match primitive parameter by passing in wrapper classes.
* For example, a <code>Boolean</code> will match a primitive <code>boolean</code>
* parameter.
*
* @param cls find method in this class
* @param methodName find method with this name
* @param parameterTypes find method with most compatible parameters
* @return The accessible method
*/
public static Method getMatchingAccessibleMethod(Class<?> cls,
String methodName, Class<?>[] parameterTypes) {
try {
Method method = cls.getMethod(methodName, parameterTypes);
MemberUtils.setAccessibleWorkaround(method);
return method;
} catch (NoSuchMethodException e) { /* SWALLOW */
}
// search through all methods
Method bestMatch = null;
Method[] methods = cls.getMethods();
for (int i = 0, size = methods.length; i < size; i++) {
if (methods[i].getName().equals(methodName)) {
// compare parameters
if (ClassUtils.isAssignable(parameterTypes, methods[i]
.getParameterTypes(), true)) {
// get accessible version of method
Method accessibleMethod = getAccessibleMethod(methods[i]);
if (accessibleMethod != null) {
if (bestMatch == null
|| MemberUtils.compareParameterTypes(
accessibleMethod.getParameterTypes(),
bestMatch.getParameterTypes(),
parameterTypes) < 0) {
bestMatch = accessibleMethod;
}
}
}
}
}
if (bestMatch != null) {
MemberUtils.setAccessibleWorkaround(bestMatch);
}
return bestMatch;
}
/**
* Gets the number of steps required needed to turn the source class into
* the destination class. This represents the number of steps in the object
* hierarchy graph.
* @param srcClass The source class
* @param destClass The destination class
* @return The cost of transforming an object
*/
private static float getObjectTransformationCost(Class<?> srcClass, Class<?> destClass) {
if (destClass.isPrimitive()) {
return getPrimitivePromotionCost(srcClass, destClass);
}
float cost = 0.0f;
while (srcClass != null && !destClass.equals(srcClass)) {
if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) {
// slight penalty for interface match.
// we still want an exact match to override an interface match,
// but
// an interface match should override anything where we have to
// get a superclass.
cost += 0.25f;
break;
}
cost++;
srcClass = srcClass.getSuperclass();
}
/*
* If the destination class is null, we've travelled all the way up to
* an Object match. We'll penalize this by adding 1.5 to the cost.
*/
if (srcClass == null) {
cost += 1.5f;
}
return cost;
}
/**
* Gets the number of steps required needed to turn the source class into
* the destination class. This represents the number of steps in the object
* hierarchy graph.
* @param srcClass The source class
* @param destClass The destination class
* @return The cost of transforming an object
*/
private static float getObjectTransformationCost(Class<?> srcClass, Class<?> destClass) {
if (destClass.isPrimitive()) {
return getPrimitivePromotionCost(srcClass, destClass);
}
float cost = 0.0f;
while (srcClass != null && !destClass.equals(srcClass)) {
if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) {
// slight penalty for interface match.
// we still want an exact match to override an interface match,
// but
// an interface match should override anything where we have to
// get a superclass.
cost += 0.25f;
break;
}
cost++;
srcClass = srcClass.getSuperclass();
}
/*
* If the destination class is null, we've travelled all the way up to
* an Object match. We'll penalize this by adding 1.5 to the cost.
*/
if (srcClass == null) {
cost += 1.5f;
}
return cost;
}
/**
* Gets the number of steps required needed to turn the source class into the
* destination class. This represents the number of steps in the object hierarchy
* graph.
* @param srcClass The source class
* @param destClass The destination class
* @return The cost of transforming an object
*/
private static float getObjectTransformationCost(Class<?> srcClass,
Class<?> destClass) {
if (destClass.isPrimitive()) {
return getPrimitivePromotionCost(srcClass, destClass);
}
float cost = 0.0f;
while (destClass != null && !destClass.equals(srcClass)) {
if (destClass.isInterface()
&& ClassUtils.isAssignable(srcClass, destClass)) {
// slight penalty for interface match.
// we still want an exact match to override an interface match,
// but
// an interface match should override anything where we have to
// get a superclass.
cost += 0.25f;
break;
}
cost++;
destClass = destClass.getSuperclass();
}
/*
* If the destination class is null, we've travelled all the way up to
* an Object match. We'll penalize this by adding 1.5 to the cost.
*/
if (destClass == null) {
cost += 1.5f;
}
return cost;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void populateItem(final ListItem<ConnConfProperty> item) {
final ConnConfProperty property = item.getModelObject();
final String label = StringUtils.isBlank(property.getSchema().getDisplayName())
? property.getSchema().getName() : property.getSchema().getDisplayName();
final FieldPanel<? extends Serializable> field;
boolean required = false;
boolean isArray = false;
if (property.getSchema().isConfidential()
|| IdMConstants.GUARDED_STRING.equalsIgnoreCase(property.getSchema().getType())
|| IdMConstants.GUARDED_BYTE_ARRAY.equalsIgnoreCase(property.getSchema().getType())) {
field = new AjaxPasswordFieldPanel("panel", label, new Model<>(), false);
((PasswordTextField) field.getField()).setResetPassword(false);
required = property.getSchema().isRequired();
} else {
Class<?> propertySchemaClass;
try {
propertySchemaClass = ClassUtils.getClass(property.getSchema().getType());
if (ClassUtils.isPrimitiveOrWrapper(propertySchemaClass)) {
propertySchemaClass = ClassUtils.primitiveToWrapper(propertySchemaClass);
}
} catch (ClassNotFoundException e) {
LOG.error("Error parsing attribute type", e);
propertySchemaClass = String.class;
}
if (ClassUtils.isAssignable(Number.class, propertySchemaClass)) {
@SuppressWarnings("unchecked")
Class<Number> numberClass = (Class<Number>) propertySchemaClass;
field = new AjaxSpinnerFieldPanel.Builder<>().build("panel", label, numberClass, new Model<>());
required = property.getSchema().isRequired();
} else if (ClassUtils.isAssignable(Boolean.class, propertySchemaClass)) {
field = new AjaxCheckBoxPanel("panel", label, new Model<>());
} else {
field = new AjaxTextFieldPanel("panel", label, new Model<>());
required = property.getSchema().isRequired();
}
if (propertySchemaClass.isArray()) {
isArray = true;
}
}
field.setIndex(item.getIndex());
field.setTitle(property.getSchema().getHelpMessage(), true);
final AbstractFieldPanel<? extends Serializable> fieldPanel;
if (isArray) {
final MultiFieldPanel multiFieldPanel = new MultiFieldPanel.Builder(
new PropertyModel<>(property, "values")).setEventTemplate(true).build("panel", label, field);
item.add(multiFieldPanel);
fieldPanel = multiFieldPanel;
} else {
setNewFieldModel(field, property.getValues());
item.add(field);
fieldPanel = field;
}
if (required) {
fieldPanel.addRequiredLabel();
}
if (withOverridable) {
fieldPanel.showExternAction(addCheckboxToggle(property));
}
}
private static boolean isSpecificConf(final AuthModuleConf conf, final Class<? extends AuthModuleConf> clazz) {
return ClassUtils.isAssignable(clazz, conf.getClass());
}
private boolean isSpecificConf(final AuthModuleConf conf, final Class<? extends AuthModuleConf> clazz) {
return ClassUtils.isAssignable(clazz, conf.getClass());
}
/**
* <p> Checks if the subject type may be implicitly cast to the target class
* following the Java generics rules. </p>
*
* @param type the subject type to be assigned to the target type
* @param toClass the target class
* @return true if <code>type</code> is assignable to <code>toClass</code>.
*/
private static boolean isAssignable(Type type, Class<?> toClass) {
if (type == null) {
// consistency with ClassUtils.isAssignable() behavior
return toClass == null || !toClass.isPrimitive();
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toClass == null) {
return false;
}
// all types are assignable to themselves
if (toClass.equals(type)) {
return true;
}
if (type instanceof Class<?>) {
// just comparing two classes
return ClassUtils.isAssignable((Class<?>) type, toClass);
}
if (type instanceof ParameterizedType) {
// only have to compare the raw type to the class
return isAssignable(getRawType((ParameterizedType) type), toClass);
}
// *
if (type instanceof TypeVariable<?>) {
// if any of the bounds are assignable to the class, then the
// type is assignable to the class.
for (Type bound : ((TypeVariable<?>) type).getBounds()) {
if (isAssignable(bound, toClass)) {
return true;
}
}
return false;
}
// the only classes to which a generic array type can be assigned
// are class Object and array classes
if (type instanceof GenericArrayType) {
return toClass.equals(Object.class)
|| toClass.isArray()
&& isAssignable(((GenericArrayType) type).getGenericComponentType(), toClass
.getComponentType());
}
// wildcard types are not assignable to a class (though one would think
// "? super Object" would be assignable to Object)
if (type instanceof WildcardType) {
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p> Checks if the subject type may be implicitly cast to the target class
* following the Java generics rules. </p>
*
* @param type the subject type to be assigned to the target type
* @param toClass the target class
* @return true if <code>type</code> is assignable to <code>toClass</code>.
*/
private static boolean isAssignable(Type type, Class<?> toClass) {
if (type == null) {
// consistency with ClassUtils.isAssignable() behavior
return toClass == null || !toClass.isPrimitive();
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toClass == null) {
return false;
}
// all types are assignable to themselves
if (toClass.equals(type)) {
return true;
}
if (type instanceof Class<?>) {
// just comparing two classes
return ClassUtils.isAssignable((Class<?>) type, toClass);
}
if (type instanceof ParameterizedType) {
// only have to compare the raw type to the class
return isAssignable(getRawType((ParameterizedType) type), toClass);
}
// *
if (type instanceof TypeVariable<?>) {
// if any of the bounds are assignable to the class, then the
// type is assignable to the class.
for (Type bound : ((TypeVariable<?>) type).getBounds()) {
if (isAssignable(bound, toClass)) {
return true;
}
}
return false;
}
// the only classes to which a generic array type can be assigned
// are class Object and array classes
if (type instanceof GenericArrayType) {
return toClass.equals(Object.class)
|| toClass.isArray()
&& isAssignable(((GenericArrayType) type).getGenericComponentType(), toClass
.getComponentType());
}
// wildcard types are not assignable to a class (though one would think
// "? super Object" would be assignable to Object)
if (type instanceof WildcardType) {
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p> Checks if the subject type may be implicitly cast to the target class
* following the Java generics rules. </p>
*
* @param type the subject type to be assigned to the target type
* @param toClass the target class
* @return true if <code>type</code> is assignable to <code>toClass</code>.
*/
private static boolean isAssignable(final Type type, final Class<?> toClass) {
if (type == null) {
// consistency with ClassUtils.isAssignable() behavior
return toClass == null || !toClass.isPrimitive();
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toClass == null) {
return false;
}
// all types are assignable to themselves
if (toClass.equals(type)) {
return true;
}
if (type instanceof Class<?>) {
// just comparing two classes
return ClassUtils.isAssignable((Class<?>) type, toClass);
}
if (type instanceof ParameterizedType) {
// only have to compare the raw type to the class
return isAssignable(getRawType((ParameterizedType) type), toClass);
}
// *
if (type instanceof TypeVariable<?>) {
// if any of the bounds are assignable to the class, then the
// type is assignable to the class.
for (final Type bound : ((TypeVariable<?>) type).getBounds()) {
if (isAssignable(bound, toClass)) {
return true;
}
}
return false;
}
// the only classes to which a generic array type can be assigned
// are class Object and array classes
if (type instanceof GenericArrayType) {
return toClass.equals(Object.class)
|| toClass.isArray()
&& isAssignable(((GenericArrayType) type).getGenericComponentType(), toClass
.getComponentType());
}
// wildcard types are not assignable to a class (though one would think
// "? super Object" would be assignable to Object)
if (type instanceof WildcardType) {
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
protected DynamoDBQueryCriteria<T, ID> addCriteria(DynamoDBQueryCriteria<T, ID> criteria, Part part, Iterator<Object> iterator) {
if (part.shouldIgnoreCase().equals(IgnoreCaseType.ALWAYS))
throw new UnsupportedOperationException("Case insensitivity not supported");
Class<?> leafNodePropertyType = part.getProperty().getLeafProperty().getType();
PropertyPath leafNodePropertyPath = part.getProperty().getLeafProperty();
String leafNodePropertyName = leafNodePropertyPath.toDotPath();
if (leafNodePropertyName.indexOf(".") != -1)
{
int index = leafNodePropertyName.lastIndexOf(".");
leafNodePropertyName = leafNodePropertyName.substring(index);
}
switch (part.getType()) {
case IN:
Object in = iterator.next();
Assert.notNull(in, "Creating conditions on null parameters not supported: please specify a value for '"
+ leafNodePropertyName + "'");
boolean isIterable = ClassUtils.isAssignable(in.getClass(), Iterable.class);
boolean isArray = ObjectUtils.isArray(in);
Assert.isTrue(isIterable || isArray, "In criteria can only operate with Iterable or Array parameters");
Iterable<?> iterable = isIterable ? ((Iterable<?>) in) : Arrays.asList(ObjectUtils.toObjectArray(in));
return criteria.withPropertyIn(leafNodePropertyName, iterable, leafNodePropertyType);
case CONTAINING:
return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.CONTAINS,
iterator.next(), leafNodePropertyType);
case STARTING_WITH:
return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.BEGINS_WITH,
iterator.next(), leafNodePropertyType);
case BETWEEN:
Object first = iterator.next();
Object second = iterator.next();
return criteria.withPropertyBetween(leafNodePropertyName, first, second, leafNodePropertyType);
case AFTER:
case GREATER_THAN:
return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.GT, iterator.next(),
leafNodePropertyType);
case BEFORE:
case LESS_THAN:
return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.LT, iterator.next(),
leafNodePropertyType);
case GREATER_THAN_EQUAL:
return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.GE, iterator.next(),
leafNodePropertyType);
case LESS_THAN_EQUAL:
return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.LE, iterator.next(),
leafNodePropertyType);
case IS_NULL:
return criteria.withNoValuedCriteria(leafNodePropertyName, ComparisonOperator.NULL);
case IS_NOT_NULL:
return criteria.withNoValuedCriteria(leafNodePropertyName, ComparisonOperator.NOT_NULL);
case TRUE:
return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.EQ, Boolean.TRUE,
leafNodePropertyType);
case FALSE:
return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.EQ, Boolean.FALSE,
leafNodePropertyType);
case SIMPLE_PROPERTY:
return criteria.withPropertyEquals(leafNodePropertyName, iterator.next(), leafNodePropertyType);
case NEGATING_SIMPLE_PROPERTY:
return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.NE, iterator.next(),
leafNodePropertyType);
default:
throw new IllegalArgumentException("Unsupported keyword " + part.getType());
}
}