List of usage examples for java.lang Class isAssignableFrom
@HotSpotIntrinsicCandidate public native boolean isAssignableFrom(Class<?> cls);
From source file:de.iteratec.iteraplan.businesslogic.service.SavedQueryXmlHelper.java
/** * Loads a query from database/*w w w . j av a2 s . co m*/ * * @param <T> The XML dto class the XML content reflects * @param clazz The XML dto class the XML content reflects * @param schemaName The URI of the schema that will be used to validate the XML query * @param savedQuery the query object * @return The object tree reflecting the XML query. Instance of a JAXB-marshallable class */ @SuppressWarnings("unchecked") public static <T extends SerializedQuery<? extends ReportMemBean>> T loadQuery(Class<T> clazz, String schemaName, SavedQuery savedQuery) { if (!ReportType.LANDSCAPE.equals(savedQuery.getType()) && clazz.isAssignableFrom(LandscapeDiagramXML.class)) { LOGGER.error("requested QueryType ('{0}') does not fit the required QueryType ('{1}')", ReportType.LANDSCAPE, savedQuery.getType()); throw new IteraplanBusinessException(IteraplanErrorMessages.INVALID_REQUEST_PARAMETER, "savedQueryType"); } try { String content = savedQuery.getContent(); if (content == null || content.length() <= 0) { throw new IteraplanTechnicalException(IteraplanErrorMessages.LOAD_QUERY_EXCEPTION); } Reader queryDefinitionReader = null; try { Schema schema = getSchema(schemaName); JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setSchema(schema); queryDefinitionReader = new StringReader(content); return (T) unmarshaller.unmarshal(queryDefinitionReader); } finally { IOUtils.closeQuietly(queryDefinitionReader); } } catch (SAXException e) { LOGGER.error("SAXException in SavedQueryServiceImpl#loadQuery " + e.getLocalizedMessage()); throw new IteraplanTechnicalException(IteraplanErrorMessages.INTERNAL_ERROR, e); } catch (JAXBException e) { LOGGER.error("JAXBException in SavedQueryServiceImpl#loadQuery " + e.getLocalizedMessage()); throw new IteraplanTechnicalException(IteraplanErrorMessages.INTERNAL_ERROR, e); } }
From source file:Main.java
/** * Use reflection to access a URL[] getURLs or URL[] getClasspath method so * that non-URLClassLoader class loaders, or class loaders that override * getURLs to return null or empty, can provide the true classpath info. * /*from w w w. j av a2 s. c o m*/ * @param cl * @return the urls */ public static URL[] getClassLoaderURLs(ClassLoader cl) { URL[] urls = {}; try { Class returnType = urls.getClass(); Class[] parameterTypes = {}; Class clClass = cl.getClass(); Method getURLs = clClass.getMethod("getURLs", parameterTypes); if (returnType.isAssignableFrom(getURLs.getReturnType())) { Object[] args = {}; urls = (URL[]) getURLs.invoke(cl, args); } if (urls == null || urls.length == 0) { Method getCp = clClass.getMethod("getClasspath", parameterTypes); if (returnType.isAssignableFrom(getCp.getReturnType())) { Object[] args = {}; urls = (URL[]) getCp.invoke(cl, args); } } } catch (Exception ignore) { } return urls; }
From source file:com.brienwheeler.svc.monitor.telemetry.impl.TelemetryServiceBaseTestUtils.java
@SuppressWarnings("unchecked") public static <T> T findProcessor(TelemetryServiceBase telemetryServiceBase, Class<T> clazz) { List<ITelemetryInfoProcessor> processors = (List<ITelemetryInfoProcessor>) ReflectionTestUtils .getField(telemetryServiceBase, "processors"); if (processors != null) { for (ITelemetryInfoProcessor proc : processors) if (clazz.isAssignableFrom(proc.getClass())) return clazz.cast(proc); }/* w w w. j a va 2 s . c o m*/ throw new IllegalStateException("no " + clazz.getSimpleName() + " found in test context!"); }
From source file:it.unibo.alchemist.language.protelis.util.ReflectionUtils.java
/** * @param method/*w w w . java 2 s.c o m*/ * the methods to invoke * @param target * the target object. It can be null, if the method which is * being invoked is static * @param args * the arguments for the method * @return the result of the invocation, or an {@link IllegalStateException} * if something goes wrong. */ public static Object invokeMethod(final Method method, final Object target, final Object[] args) { final Class<?>[] params = method.getParameterTypes(); List<Object> list = new ArrayList<Object>(); for (int i = 0; i < args.length; i++) { final Class<?> expected = params[i]; final Object actual = args[i]; if (!expected.isAssignableFrom(actual.getClass()) && PrimitiveUtils.classIsNumber(expected)) { // TODO: Removed .get() list.add(PrimitiveUtils.castIfNeeded(expected, (Number) actual)); // list.add(PrimitiveUtils.castIfNeeded(expected, (Number) actual).get()); } else { list.add(actual); } } Object[] actualArgs = list.toArray(); try { return method.invoke(target, actualArgs); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { L.error(e); throw new IllegalStateException( "Cannot invoke " + method + " with arguments " + Arrays.toString(args) + " on " + target, e); } }
From source file:it.unibo.alchemist.language.protelis.util.ReflectionUtils.java
private static Method loadBestMethod(final Class<?> clazz, final String methodName, final Class<?>[] argClass) { Objects.requireNonNull(clazz, "The class on which the method will be invoked can not be null."); Objects.requireNonNull(methodName, "Method name can not be null."); Objects.requireNonNull(argClass, "Method arguments can not be null."); /*//ww w . j ava 2 s .c o m * If there is a matching method, return it */ try { return clazz.getMethod(methodName, argClass); } catch (NoSuchMethodException | SecurityException e) { /* * Look it up on the cache */ /* * Deal with Java method overloading scoring methods */ final Method[] candidates = clazz.getMethods(); final List<Pair<Integer, Method>> lm = new ArrayList<>(candidates.length); for (final Method m : candidates) { // TODO: Workaround for different Method API if (m.getParameterTypes().length == argClass.length && methodName.equals(m.getName())) { final Class<?>[] params = m.getParameterTypes(); int p = 0; boolean compatible = true; for (int i = 0; compatible && i < argClass.length; i++) { final Class<?> expected = params[i]; if (expected.isAssignableFrom(argClass[i])) { /* * No downcast required, there is compatibility */ p++; } else if (!PrimitiveUtils.classIsNumber(expected)) { compatible = false; } } if (compatible) { lm.add(new Pair<>(p, m)); } } } /* * Find best */ if (lm.size() > 0) { Pair<Integer, Method> max = lm.get(0); for (Pair<Integer, Method> cPair : lm) { if (cPair.getFirst().compareTo(max.getFirst()) > 0) { max = cPair; } } return max.getSecond(); } } List<Class<?>> list = new ArrayList<>(); for (Class<?> c : argClass) { list.add(c); } final String argType = list.toString(); throw new NoSuchMethodError( methodName + "/" + argClass.length + argType + " does not exist in " + clazz + "."); }
From source file:Main.java
public static <T> T parse(final Class<T> clazz, final InputStream inputStream) { try {//from w w w .j av a 2s.c o m final JAXBContext jaxbContext = JAXBContext.newInstance(clazz); final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); final Object deserialized = jaxbUnmarshaller.unmarshal(inputStream); if (clazz.isAssignableFrom(deserialized.getClass())) { return clazz.cast(deserialized); } else { final JAXBElement<T> jaxbElement = (JAXBElement<T>) deserialized; return jaxbElement.getValue(); } } catch (final JAXBException e) { throw new RuntimeException(e); } }
From source file:com.cloudmine.api.CMApiCredentials.java
/** * If you are using CloudMine on Android, this or {@link #initialize(String, String, Object)} is the initialize method you should be calling. Works just * like {@link #initialize(String, String, String)}, but sets some important android only information * @param id/*from w w w. ja v a 2 s. co m*/ * @param apiKey * @param baseUrl the base CloudMine URL to use, if running on a non default CloudMine install * @param context either null if not running on android, or the value of getApplicationContext from your main activity. It isn't typed here so the Java sdk does not have any android dependencies * @return * @throws CreationException in addition to the reasons defined in {@link #initialize(String, String)}, also if you do not provide the application context and you're running on android */ public static synchronized CMApiCredentials initialize(String id, String apiKey, String baseUrl, Object context) throws CreationException { if (Strings.isEmpty(id) || Strings.isEmpty(apiKey) || Strings.isEmpty(baseUrl)) { throw new CreationException( "Illegal null/empty argument passed to initialize. Given id=" + id + " and apiKey=" + apiKey); } try { Class contextClass = Class.forName("android.content.Context"); boolean invalidContext = context == null || contextClass == null || !contextClass.isAssignableFrom(context.getClass()); if (invalidContext) { throw new CreationException( "Running on android and application context not provided, try passing getApplicationContext to this method"); } for (Method method : Class.forName("com.cloudmine.api.DeviceIdentifier").getMethods()) { if ("initialize".equals(method.getName())) { method.invoke(null, context); } } } catch (ClassNotFoundException e) { LOG.info("Not running on Android", e); } catch (InvocationTargetException e) { LOG.error("Exception thrown", e); } catch (IllegalAccessException e) { LOG.error("Exception thrown", e); } credentials = new CMApiCredentials(id, apiKey, baseUrl); return credentials; }
From source file:com.netflix.nicobar.core.module.ScriptModuleUtils.java
/** * Find all of the classes in the module that are subclasses or equal to the target class * @param module module to search/*from www . ja v a2 s .c om*/ * @param targetClass target type to search for * @return first instance that matches the given type */ public static Set<Class<?>> findAssignableClasses(ScriptModule module, Class<?> targetClass) { Set<Class<?>> result = new LinkedHashSet<Class<?>>(); for (Class<?> candidateClass : module.getLoadedClasses()) { if (targetClass.isAssignableFrom(candidateClass)) { result.add(candidateClass); } } return result; }
From source file:com.expressui.core.util.StringUtil.java
/** * Generates CSS style names from an object's class and all its parents in class hierarchy. * * @param prefix to prepend to style name * @param topLevelClass style names are only generated up to this top level class in the class hierarchical. Higher * level classes are ignored * @param object object to reflectively get class from * @return List of style names//from w ww . j a v a 2 s . com */ public static List<String> generateStyleNamesFromClassHierarchy(String prefix, Class topLevelClass, Object object) { List<String> styles = new ArrayList<String>(); Class currentClass = object.getClass(); while (topLevelClass.isAssignableFrom(currentClass)) { String simpleName = currentClass.getSimpleName(); String style = StringUtil.hyphenateCamelCase(simpleName); styles.add(prefix + "-" + style); currentClass = currentClass.getSuperclass(); } return styles; }
From source file:net.servicefixture.util.ReflectionUtils.java
private static boolean isConcreteSubclass(Class<?> baseClass, Class<?> clazz) { return baseClass.isAssignableFrom(clazz) && !baseClass.equals(clazz) && !clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()); }