List of usage examples for java.lang Class isAssignableFrom
@HotSpotIntrinsicCandidate public native boolean isAssignableFrom(Class<?> cls);
From source file:org.bremersee.sms.ExtensionUtils.java
/** * Transforms a XML node or a JSON map into an object. * //from w w w.j a v a 2s . c o m * @param xmlNodeOrJsonMap * the XML node or JSON map * @param valueType * the class of the target object * @param jaxbContext * the {@link JAXBContext} (can be null) * @param objectMapper * the JSON object mapper (optional) * @return the target object * @throws Exception * if transformation fails */ @SuppressWarnings("unchecked") public static <T> T transform(Object xmlNodeOrJsonMap, Class<T> valueType, JAXBContext jaxbContext, ObjectMapper objectMapper) throws Exception { if (xmlNodeOrJsonMap == null) { return null; } Validate.notNull(valueType, "valueType must not be null"); if (valueType.isAssignableFrom(xmlNodeOrJsonMap.getClass())) { return valueType.cast(xmlNodeOrJsonMap); } if (xmlNodeOrJsonMap instanceof Node) { return xmlNodeToObject((Node) xmlNodeOrJsonMap, valueType, jaxbContext); } if (xmlNodeOrJsonMap instanceof Map) { return jsonMapToObject((Map<String, Object>) xmlNodeOrJsonMap, valueType, objectMapper); } throw new IllegalArgumentException("xmlNodeOrJsonMap must be of type " + valueType + ", " + Node.class.getName() + " or of type " + Map.class.getName()); }
From source file:Main.java
/** * convert value to given type.//from w w w . j a v a 2 s. com * null safe. * * @param value value for convert * @param type will converted type * @return value while converted */ public static Object convertCompatibleType(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } else if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } else if (type == BigInteger.class) { return new BigInteger(string); } else if (type == BigDecimal.class) { return new BigDecimal(string); } else if (type == Short.class || type == short.class) { return Short.valueOf(string); } else if (type == Integer.class || type == int.class) { return Integer.valueOf(string); } else if (type == Long.class || type == long.class) { return Long.valueOf(string); } else if (type == Double.class || type == double.class) { return Double.valueOf(string); } else if (type == Float.class || type == float.class) { return Float.valueOf(string); } else if (type == Byte.class || type == byte.class) { return Byte.valueOf(string); } else if (type == Boolean.class || type == boolean.class) { return Boolean.valueOf(string); } else if (type == Date.class) { try { return new SimpleDateFormat(DATE_FORMAT).parse((String) value); } catch (ParseException e) { throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } else if (type == Class.class) { return forName((String) value); } } else if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } else if (type == short.class || type == Short.class) { return number.shortValue(); } else if (type == int.class || type == Integer.class) { return number.intValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); } else if (type == float.class || type == Float.class) { return number.floatValue(); } else if (type == double.class || type == Double.class) { return number.doubleValue(); } else if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } else if (type == BigDecimal.class) { return BigDecimal.valueOf(number.doubleValue()); } else if (type == Date.class) { return new Date(number.longValue()); } } else if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } else if (!type.isInterface()) { try { Collection result = (Collection) type.newInstance(); result.addAll(collection); return result; } catch (Throwable e) { e.printStackTrace(); } } else if (type == List.class) { return new ArrayList<>(collection); } else if (type == Set.class) { return new HashSet<>(collection); } } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.newInstance(); } catch (Throwable e) { collection = new ArrayList<>(); } } else if (type == Set.class) { collection = new HashSet<>(); } else { collection = new ArrayList<>(); } int length = Array.getLength(value); for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; }
From source file:org.geoserver.wps.ppio.ProcessParameterIO.java
public static ProcessParameterIO find(Parameter<?> p, ApplicationContext context, String mime) { // enum special treatment if (p.type.isEnum()) { return new LiteralPPIO(p.type); }//from w w w . ja v a 2 s . c o m // TODO: come up with some way to flag one as "default" List<ProcessParameterIO> all = findAll(p, context); if (all.isEmpty()) { return null; } if (mime != null) { for (ProcessParameterIO ppio : all) { if (ppio instanceof ComplexPPIO && ((ComplexPPIO) ppio).getMimeType().equals(mime)) { return ppio; } } } // if more than one sort by class hierarchy, pushing the most specific classes to the // beginning if (all.size() > 0) { Collections.sort(all, new Comparator<ProcessParameterIO>() { public int compare(ProcessParameterIO o1, ProcessParameterIO o2) { Class c1 = o1.getType(); Class c2 = o2.getType(); if (c1.equals(c2)) { return 0; } if (c1.isAssignableFrom(c2)) { return 1; } return -1; } }); } // fall back on the first found return all.get(0); }
From source file:com.excilys.ebi.bank.util.Asserts.java
public static void isAssignable(Class<?> superType, Class<?> subType, String messagePattern, Object arg) { notNull(superType, "Type to check against must not be null"); if (subType == null || !superType.isAssignableFrom(subType)) { throw new IllegalArgumentException(MessageFormatter.format(messagePattern, arg).getMessage() + subType + " is not assignable to " + superType); }// w w w . j a v a 2 s . c o m }
From source file:com.excilys.ebi.bank.util.Asserts.java
public static void isAssignable(Class<?> superType, Class<?> subType, String messagePattern, Object... args) { notNull(superType, "Type to check against must not be null"); if (subType == null || !superType.isAssignableFrom(subType)) { throw new IllegalArgumentException(MessageFormatter.arrayFormat(messagePattern, args).getMessage() + subType + " is not assignable to " + superType); }//www .ja v a2s .c o m }
From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.util.ExcelGeneratorUtils.java
public static void initDataCells(WorkbookContext wbContext, SheetContext sheetContext, int dataSetSize) { int lastDataRow = sheetContext.calculateLastDataRow(dataSetSize); for (int rowIndex = sheetContext.getFirstDataRowNumber(); rowIndex <= lastDataRow; rowIndex++) { Row row = ExcelUtils.getOrCreateRow(sheetContext.getSheet(), rowIndex); for (ColumnContext sheetColumn : sheetContext.getColumns()) { Cell cell = row.createCell(sheetColumn.getColumnNumber()); CellStyle dataStyle = wbContext.getStyles().get(IteraExcelStyle.DATA); cell.setCellStyle(dataStyle); FeatureExpression<?> expression = sheetColumn.getFeatureExpression(); if (expression instanceof PrimitivePropertyExpression) { Class<?> type = ((PrimitivePropertyExpression) expression).getType().getEncapsulatedType(); if (type.isAssignableFrom(Date.class) || (BuiltinPrimitiveType.DURATION.equals(expression.getType()))) { CellStyle dateStyle = wbContext.getStyles().get(IteraExcelStyle.DATA_DATE); cell.setCellStyle(dateStyle); }/*from ww w .j a v a2 s . co m*/ } } } }
From source file:de.pribluda.android.jsonmarshaller.JSONUnmarshaller.java
/** * recursively populate array out of hierarchy of JSON Objects * * @param arrayClass original array class * @param json json object in question * @return/*from w w w. j ava 2 s . c o m*/ */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static Object populateRecursiveList(Class arrayClass, Class clazz, Object json) throws JSONException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { if (arrayClass.isAssignableFrom(List.class) && json instanceof JSONArray) { final int length = ((JSONArray) json).length(); Object retval = new ArrayList(); for (int i = 0; i < length; i++) { ((List) retval).add(populateRecursive(clazz, ((JSONArray) json).get(i))); } return retval; } else { // this is leaf object, JSON needs to be unmarshalled, if (json instanceof JSONObject) { return unmarshall((JSONObject) json, arrayClass); } else { // while all others can be returned verbatim return json; } } }
From source file:net.sf.morph.util.TransformerUtils.java
private static Class[] getClassIntersection(Transformer[] transformers, ClassStrategy strategy) { Set s = ContainerUtils.createOrderedSet(); s.addAll(Arrays.asList(strategy.get(transformers[0]))); for (int i = 1; i < transformers.length; i++) { Set survivors = ContainerUtils.createOrderedSet(); Class[] c = strategy.get(transformers[i]); for (int j = 0; j < c.length; j++) { if (s.contains(c[j])) { survivors.add(c[j]);//w ww. j a va2 s . c o m break; } if (c[j] == null) { break; } for (Iterator it = s.iterator(); it.hasNext();) { Class next = (Class) it.next(); if (next != null && next.isAssignableFrom(c[j])) { survivors.add(c[j]); break; } } } if (!survivors.containsAll(s)) { for (Iterator it = s.iterator(); it.hasNext();) { Class next = (Class) it.next(); if (survivors.contains(next) || next == null) { break; } for (int j = 0; j < c.length; j++) { if (c[j] != null && c[j].isAssignableFrom(next)) { survivors.add(next); break; } } } } s = survivors; } return s.isEmpty() ? CLASS_NONE : (Class[]) s.toArray(new Class[s.size()]); }
From source file:Main.java
public static boolean isTypeCompatibleWithArgumentType(Class<?> actual, Class<?> formal) { if (actual.isPrimitive() && formal.isPrimitive()) { return isConvertible(actual, formal); } else if (actual.isPrimitive()) { return isConvertible(actual, convertToPrimitiveType(formal)); } else if (formal.isPrimitive()) { return isConvertible(convertToPrimitiveType(actual), formal); } else {/*w w w . ja v a 2 s. c om*/ return formal.isAssignableFrom(actual); } }
From source file:com.addthis.codec.config.Configs.java
public static ConfigValue expandSugar(Class<?> type, ConfigValue config, PluginRegistry pluginRegistry) { if ((type != null) && type.isAssignableFrom(ConfigValue.class)) { return ConfigValueFactory.fromAnyRef(config.unwrapped(), "unchanged for raw ConfigValue field " + config.origin().description()); }//from ww w.java 2 s . c o m CodableClassInfo typeInfo = new CodableClassInfo(type, pluginRegistry.config(), pluginRegistry); PluginMap pluginMap = typeInfo.getPluginMap(); ConfigValue valueOrResolvedRoot = resolveType(type, config, pluginMap); if (valueOrResolvedRoot.valueType() != ConfigValueType.OBJECT) { return valueOrResolvedRoot; } ConfigObject root = (ConfigObject) valueOrResolvedRoot; String classField = pluginMap.classField(); if (root.get(classField) != null) { try { type = pluginMap.getClass((String) root.get(classField).unwrapped()); } catch (ClassNotFoundException ignored) { // try not to throw exceptions or at least checked exceptions from this helper method } } return expandSugarSkipResolve(type, root, pluginRegistry); }