List of usage examples for java.lang Class isAssignableFrom
@HotSpotIntrinsicCandidate public native boolean isAssignableFrom(Class<?> cls);
From source file:io.twipple.springframework.data.clusterpoint.convert.support.CustomConversions.java
/** * Inspects the given {@link org.springframework.core.convert.converter.GenericConverter.ConvertiblePair} for ones * that have a source compatible type as source. Additionally checks assignability of the target type if one is * given./*from w w w .j a v a 2 s. co m*/ * * @param sourceType must not be {@literal null}. * @param requestedTargetType can be {@literal null}. * @param pairs must not be {@literal null}. * @return */ private static Class<?> getCustomTarget(@NotNull Class<?> sourceType, Class<?> requestedTargetType, @NotNull Iterable<GenericConverter.ConvertiblePair> pairs) { Assert.notNull(sourceType); Assert.notNull(pairs); for (GenericConverter.ConvertiblePair typePair : pairs) { if (typePair.getSourceType().isAssignableFrom(sourceType)) { Class<?> targetType = typePair.getTargetType(); if (requestedTargetType == null || targetType.isAssignableFrom(requestedTargetType)) { return targetType; } } } return null; }
From source file:org.openinfinity.core.util.AspectUtil.java
/** * Returns the specified annotation./*from ww w . j av a2s .co m*/ * * @param joinPoint Represents the join point. * @return * @return LogLevel representing the log level. */ public static <T extends Annotation> T getAnnotation(JoinPoint joinPoint, Class<T> requiredAnnotationClass) { Method[] methods = joinPoint.getTarget().getClass().getMethods(); for (Method method : methods) { if (method.getName().equals(joinPoint.getSignature().getName())) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (requiredAnnotationClass.isAssignableFrom(annotation.getClass())) { return (T) annotation; } } } } throw new SystemException(new AopConfigException("Annotation not found.")); }
From source file:net.servicefixture.converter.ObjectConverter.java
/** * Use the jexl expression to get the object from the * <code>GlobalContext</code>. * /*www. j a v a 2s . c om*/ * Note: the expression must follow <testTableKey>. <request[i]>| * <response>.* pattern. * * Throws FixtureException if the destType is not assignable from the object * type. */ private static Object evaluateJexlToken(String expression, Class<?> destType, boolean checkType) { Object result = JexlEvaluator.evaluate(expression, GlobalContext.getGlobalJexlContext()); if (result != null && checkType) { Class<?> resultType = result.getClass(); if (!destType.isAssignableFrom(resultType) && !(destType.isPrimitive() && resultType.getName().equalsIgnoreCase("java.lang." + destType.getName()))) { throw new ServiceFixtureException("Expression " + expression + " returns a object(" + resultType.getName() + ") that is not " + destType.getName() + " type."); } } return result; }
From source file:org.bremersee.sms.ExtensionUtils.java
/** * Transforms a XML node or a JSON map into an object. * /*from ww w . j av a 2s . c om*/ * @param xmlNodeOrJsonMap * the XML node or JSON map * @param valueType * the class of the target object * @param jaxbContextOrObjectMapper * a {@link JAXBContext} or a {@link ObjectMapper} (can be null) * @return the target object * @throws Exception * if transformation fails * @deprecated Use * {@link ExtensionUtils#transform(Object, Class, JAXBContext, ObjectMapper)} * instead. */ @Deprecated @SuppressWarnings("unchecked") public static <T> T transform(Object xmlNodeOrJsonMap, Class<T> valueType, Object jaxbContextOrObjectMapper) 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) { JAXBContext jaxbContext; if (jaxbContextOrObjectMapper != null && jaxbContextOrObjectMapper instanceof JAXBContext) { jaxbContext = (JAXBContext) jaxbContextOrObjectMapper; } else { jaxbContext = null; } return xmlNodeToObject((Node) xmlNodeOrJsonMap, valueType, jaxbContext); } if (xmlNodeOrJsonMap instanceof Map) { ObjectMapper objectMapper; if (jaxbContextOrObjectMapper != null && jaxbContextOrObjectMapper instanceof ObjectMapper) { objectMapper = (ObjectMapper) jaxbContextOrObjectMapper; } else { objectMapper = null; } return jsonMapToObject((Map<String, Object>) xmlNodeOrJsonMap, valueType, objectMapper); } throw new IllegalArgumentException( "xmlNodeOrJsonMap must be of type " + Node.class.getName() + " or of type " + Map.class.getName()); }
From source file:com.dosport.system.utils.ReflectionUtils.java
public static List<Class<?>> getAllAssignedClass(Class<?> cls) throws IOException, ClassNotFoundException { List<Class<?>> classes = new ArrayList<Class<?>>(); for (Class<?> c : getClasses(cls)) { if (cls.isAssignableFrom(c) && !cls.equals(c)) { classes.add(c);/*from ww w . j a v a2 s . co m*/ } } return classes; }
From source file:android.support.test.espresso.web.model.ModelCodec.java
private static JSONStringer encodeHelper(Object javaObject, JSONStringer stringer) throws JSONException { if (null == javaObject) { stringer.value(javaObject);// www . jav a 2 s.c o m } else if (javaObject instanceof Map) { stringer.object(); Set<Map.Entry> entries = ((Map) javaObject).entrySet(); for (Map.Entry entry : entries) { stringer.key(entry.getKey().toString()); encodeHelper(entry.getValue(), stringer); } stringer.endObject(); } else if (javaObject instanceof Iterable) { stringer.array(); for (Object obj : ((Iterable) javaObject)) { encodeHelper(obj, stringer); } stringer.endArray(); } else if (javaObject instanceof Object[]) { stringer.array(); for (Object obj : ((Object[]) javaObject)) { encodeHelper(obj, stringer); } stringer.endArray(); } else if (javaObject instanceof JSONAble) { JSONObject jsonObj = new JSONObject(((JSONAble) javaObject).toJSONString()); stringer.value(jsonObj); } else { boolean converted = false; for (Class valuableClazz : VALUEABLE_CLASSES) { if (valuableClazz.isAssignableFrom(javaObject.getClass())) { converted = true; stringer.value(javaObject); } } checkState(converted, "%s: not encodable. Want one of: %s", javaObject.getClass(), VALUEABLE_CLASSES); } return stringer; }
From source file:com.hurence.logisland.documentation.DocGenerator.java
/** * Generates documentation into the work/docs dir specified from a specified set of class *///w w w . jav a2s .co m public static void generate(final File docsDirectory, final String writerType) { Map<String, Class> extensionClasses = new TreeMap<>(); PluginLoader.getRegistry().forEach((className, classLoader) -> { try { extensionClasses.put(className, classLoader.loadClass(className)); } catch (Exception e) { logger.error("Unable to load class " + className, e); } }); ClassFinder.findClasses(clazz -> { if (!clazz.startsWith("BOOT-INF") && clazz.contains("logisland") && !clazz.contains("Mock") && !clazz.contains("shade")) { try { Class c = Class.forName(clazz); if (c.isAssignableFrom(ConfigurableComponent.class) && !Modifier.isAbstract(c.getModifiers())) { extensionClasses.put(c.getSimpleName(), c); } } catch (Throwable e) { logger.error("Unable to load class " + clazz + " : " + e.getMessage()); } } return true; // return false if you don't want to see any more classes }); docsDirectory.mkdirs(); // write headers for single rst file if (writerType.equals("rst")) { final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType); if (baseDocumenationFile.exists()) baseDocumenationFile.delete(); try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) { writer.println("Components"); writer.println("=========="); writer.println( "You'll find here the list of all usable Processors, Engines, Services and other components " + "that can be usable out of the box in your analytics streams"); writer.println(); } catch (FileNotFoundException e) { logger.warn(e.getMessage()); } } else if (writerType.equals("json")) { final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType); if (baseDocumenationFile.exists()) baseDocumenationFile.delete(); try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) { writer.println("["); } catch (FileNotFoundException e) { logger.warn(e.getMessage()); } } Class[] sortedExtensionsClasses = new Class[extensionClasses.size()]; extensionClasses.values(). toArray(sortedExtensionsClasses); Arrays.sort(sortedExtensionsClasses, new Comparator<Class>() { @Override public int compare(Class s1, Class s2) { // the +1 is to avoid including the '.' in the extension and to avoid exceptions // EDIT: // We first need to make sure that either both files or neither file // has an extension (otherwise we'll end up comparing the extension of one // to the start of the other, or else throwing an exception) final int s1Dot = s1.getName().lastIndexOf('.'); final int s2Dot = s2.getName().lastIndexOf('.'); if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither String s1Name = s1.getName().substring(s1Dot + 1); String s2Name = s2.getName().substring(s2Dot + 1); return s1Name.compareTo(s2Name); } else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first return -1; } else { // only s1 has an extension, so s1 goes second return 1; } } }); logger.info("Generating " + writerType + " documentation for " + Arrays.stream(sortedExtensionsClasses). count() + " components in: " + docsDirectory); Arrays.stream(sortedExtensionsClasses). forEach(extensionClass -> { final Class componentClass = extensionClass.asSubclass(ConfigurableComponent.class); try { document(docsDirectory, componentClass, writerType); } catch (Exception e) { logger.error("Unexpected error for " + extensionClass, e); } }); if (writerType.equals("json")) { final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType); try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) { writer.println("]"); } catch (FileNotFoundException e) { logger.warn(e.getMessage()); } } }
From source file:com.braffdev.server.core.utilities.HandlerClassListInflater.java
/** * Instantiates the class the given class config contains.<br /> * This method checks whether the class is assignable from the given target class. * * @param classConfig the config.// ww w. java 2 s. co m * @param targetClazz the clazz. * @return */ @SuppressWarnings("unchecked") private static <T extends Handler> T createInstance(ClassConfig classConfig, Class<T> targetClazz) { String clazz = classConfig.getClazz(); if (StringUtils.isNotBlank(clazz)) { try { // get class Class<?> handlerClass = loadClass(clazz); // check if the class is a assignable from the given target class if (targetClazz.isAssignableFrom(handlerClass)) { return (T) handlerClass.newInstance(); } else { LOGGER.error("The class '" + clazz + "' is unrelated to " + targetClazz + ". Skipping.."); } } catch (Exception e) { LOGGER.error(e); } } return null; }
From source file:nz.co.senanque.validationengine.ValidationUtils.java
public static Comparable<?> convertTo(final Class<Comparable<?>> clazz, Object obj) { if (obj == null) { return null; }/* w ww . ja v a2s . c om*/ if (clazz.isAssignableFrom(obj.getClass())) { return (Comparable<?>) obj; } final String oStr = String.valueOf(obj); if (clazz.equals(String.class)) { return oStr; } if (clazz.equals(Long.class) || clazz.equals(Long.TYPE)) { if (Number.class.isAssignableFrom(obj.getClass())) { return new Long(((Number) obj).longValue()); } return Long.valueOf(oStr); } if (clazz.equals(Integer.class) || clazz.equals(Integer.TYPE)) { if (Number.class.isAssignableFrom(obj.getClass())) { return new Integer(((Number) obj).intValue()); } return Integer.valueOf(oStr); } if (clazz.equals(Double.class) || clazz.equals(Double.TYPE)) { if (Number.class.isAssignableFrom(obj.getClass())) { return new Double(((Number) obj).doubleValue()); } return Double.valueOf(oStr); } if (clazz.equals(Float.class) || clazz.equals(Float.TYPE)) { if (Number.class.isAssignableFrom(obj.getClass())) { return new Float(((Number) obj).floatValue()); } return Float.valueOf(oStr); } if (clazz.equals(BigDecimal.class)) { return new BigDecimal(oStr); } if (clazz.equals(java.util.Date.class)) { return java.sql.Date.valueOf(oStr); } if (clazz.equals(java.sql.Date.class)) { return java.sql.Date.valueOf(oStr); } return null; }
From source file:Main.java
@SuppressWarnings("unchecked") public static Collection<Object> newCollection(Class<?> targetClass, int length) throws InstantiationException, IllegalAccessException { if (targetClass.isInterface()) { if (Set.class.isAssignableFrom(targetClass)) { if (SortedSet.class.isAssignableFrom(targetClass)) return new TreeSet<Object>(); return new HashSet<Object>(length); }// w ww .j a va 2 s . com if (targetClass.isAssignableFrom(ArrayList.class)) return new ArrayList<Object>(length); throw new IllegalArgumentException("Unsupported collection interface: " + targetClass); } return (Collection<Object>) targetClass.newInstance(); }