List of usage examples for java.lang Class isAssignableFrom
@HotSpotIntrinsicCandidate public native boolean isAssignableFrom(Class<?> cls);
From source file:lapin.load.Loader.java
static private Object _impSubrs(Object pkgname, Class clazz, Symbol indicator, Object export, Env env) throws IllegalAccessException { Lisp lisp = env.lisp();/*from w w w.j a v a2 s. c o m*/ Field[] fields = clazz.getFields(); Class subrClass = Subr.class; for (int i = 0; i < fields.length; i++) { Field f = fields[i]; int m = f.getModifiers(); if (!Modifier.isStatic(m)) continue; if (!subrClass.isAssignableFrom(f.getType())) continue; Subr subr = Data.subr(f.get(null)); Symbol sym = Data.symbol(lisp.getObarray().intern(pkgname, subr.name()).nth(0)); if (!Data.isNot(export)) lisp.getObarray().exp(pkgname, sym); Object old = lisp.getProp(sym, indicator, Symbols.NIL); if (!Data.isNot(old)) throw new LispException( "conflict detected while importing subrs " + "defined in ~S: name=~S indicator=~S", Lists.list(clazz, sym, indicator)); lisp.setProp(sym, indicator, subr); if (subr instanceof Prop) lisp.setProp((Prop) subr, SysSymbols.SUBR_FIELD, f); } return Symbols.T; }
From source file:org.openmrs.module.webservices.rest.util.ReflectionUtil.java
/** * If clazz implements genericInterface<T, U, ...>, this method returns the parameterized type * with the given index from that interface. This method will recursively look at superclasses * until it finds one implementing the requested interface * //from w ww . j av a2 s . com * @should find genericInterface on a superclass if clazz does not directly implement it * @should ignore type variables on the declaring interface * @should not inspect superclasses of the specified genericInterface */ @SuppressWarnings("rawtypes") public static Class getParameterizedTypeFromInterface(Class<?> clazz, Class<?> genericInterface, int index) { for (Type t : clazz.getGenericInterfaces()) { if (t instanceof ParameterizedType && ((Class) ((ParameterizedType) t).getRawType()).equals(genericInterface)) { //if we have reached the base interface that declares the type variable T, ignore it Type pType = ((ParameterizedType) t).getActualTypeArguments()[index]; if (!(pType instanceof TypeVariable)) { return (Class) pType; } } } if (clazz.getSuperclass() != null && genericInterface.isAssignableFrom(clazz.getSuperclass())) { return getParameterizedTypeFromInterface(clazz.getSuperclass(), genericInterface, index); } return null; }
From source file:de.codesourcery.jasm16.ast.ASTUtils.java
public static <T extends ASTNode> List<T> getNodesByType(final ASTNode root, final Class<T> clazz, final boolean excludeInputNode) { final List<T> result = new ArrayList<T>(); final ISimpleASTNodeVisitor<ASTNode> visitor = new ISimpleASTNodeVisitor<ASTNode>() { @SuppressWarnings("unchecked") @Override/* ww w . j a v a 2s . c om*/ public boolean visit(ASTNode node) { if (clazz.isAssignableFrom(node.getClass())) { if (!excludeInputNode || node != root) { result.add((T) node); } } return true; } }; // do NOT change the order here, AST#parseInternal() checks // .org directives for ascending values and relies // on the fact that this method returns the nodes in-order ! visitInOrder(root, visitor); return result; }
From source file:com.google.code.activetemplates.impl.handlers.BuiltinHandlerSPI.java
private static final <T> Set<Class<T>> getClasses(String pkg, Class<T> clazz) throws Exception { pkg = pkg.replace('.', '/'); Set<Class<T>> classes = new HashSet<Class<T>>(); ResourcePatternResolver res = new PathMatchingResourcePatternResolver(); Resource[] resources = res.getResources("classpath*:" + pkg + "/*.class"); for (Resource r : resources) { String className = r.getURL().getFile(); className = className.substring(className.indexOf(pkg), className.length() - ".class".length()); className = className.replace('/', '.'); try {/* www . j a va 2 s . c o m*/ Class<?> cl = Class.forName(className); if (clazz.isAssignableFrom(cl)) { @SuppressWarnings("unchecked") Class<T> tcl = (Class<T>) cl; classes.add(tcl); } } catch (ClassNotFoundException e) { } } return classes; }
From source file:edu.ucsd.sbrg.escher.EscherConverter.java
/** * Generic method which converts the given {@link EscherMap} instance to the specified * generic parameter {@code format}, by calling the corresponding converter. * * @param map {@link EscherMap} instance to convert. * @param format Output format to convert to. * @param properties Command line options, if any. * @return An instance of {@code format} type created from the escher map. *//*from www . j ava 2s. c o m*/ @SuppressWarnings("unchecked") public static <T> T convert(EscherMap map, Class<? extends T> format, SBProperties properties) { if (format.isAssignableFrom(SBMLDocument.class)) { // File is SBML, so convert to it. Escher2SBML converter = new Escher2SBML(); configure(converter, properties); converter.setCanvasDefaultHeight(properties.getDoubleProperty(EscherOptions.CANVAS_DEFAULT_HEIGHT)); converter.setCanvasDefaultWidth(properties.getDoubleProperty(EscherOptions.CANVAS_DEFAULT_WIDTH)); converter.setDefaultCompartmentId(properties.getProperty(EscherOptions.COMPARTMENT_ID)); converter.setDefaultCompartmentName(properties.getProperty(EscherOptions.COMPARTMENT_NAME)); converter.setLayoutId(properties.getProperty(EscherOptions.LAYOUT_ID)); converter.setLayoutName(properties.getProperty(EscherOptions.LAYOUT_NAME)); converter.setNodeDepth(properties.getDoubleProperty(EscherOptions.NODE_DEPTH)); converter.setNodeLabelHeight(properties.getDoubleProperty(EscherOptions.NODE_LABEL_HEIGHT)); converter.setZ(properties.getDoubleProperty(EscherOptions.Z)); return (T) converter.convert(map); } else if (format.isAssignableFrom(Sbgn.class)) { // File is SBGN-ML, so convert to it. Escher2Standard<?> converter = configure(new Escher2SBGN(), properties); return (T) converter.convert(map); } return null; }
From source file:com.asakusafw.lang.compiler.cli.BatchCompilerCli.java
private static <T> T newInstance(ClassLoader classLoader, Class<T> type, ClassDescription aClass) { try {/* www .j a v a 2 s .c o m*/ Class<?> resolved = aClass.resolve(classLoader); if (type.isAssignableFrom(resolved) == false) { throw new DiagnosticException(Diagnostic.Level.ERROR, MessageFormat .format("{0} must be a subtype of {1}", type.getName(), aClass.getClassName())); } return resolved.asSubclass(type).newInstance(); } catch (ReflectiveOperationException e) { throw new DiagnosticException(Diagnostic.Level.ERROR, MessageFormat.format("failed to instantiate a class: {0}", aClass.getClassName()), e); } }
From source file:org.echocat.jemoni.jmx.support.SpringUtils.java
@Nullable private static Method getMethod(@Nullable Class<?> fromType, boolean expectedStatic, Class<?> returnType, @Nonnull String name, @Nullable Class<?>... parameterTypes) { final Method method; if (fromType != null) { try {//w ww .j a v a 2s. c o m method = fromType.getMethod(name, parameterTypes); } catch (NoSuchMethodException e) { throw new RuntimeException( buildMessageFor(fromType, expectedStatic, returnType, name, parameterTypes), e); } final int modifiers = method.getModifiers(); if ((expectedStatic && !isStatic(modifiers)) || (!expectedStatic && isStatic(modifiers)) || !returnType.isAssignableFrom(method.getReturnType())) { throw new RuntimeException( buildMessageFor(fromType, expectedStatic, returnType, name, parameterTypes)); } } else { method = null; } return method; }
From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java
/** * Determine whether the given method explicitly declares the given * exception or one of its superclasses, which means that an exception of * that type can be propagated as-is within a reflective invocation. * @param method the declaring method// w w w . j a v a 2s . co m * @param exceptionType the exception to throw * @return {@code true} if the exception can be thrown as-is; * {@code false} if it needs to be wrapped */ public static boolean declaresException(Method method, Class<?> exceptionType) { Assert.notNull(method, "Method must not be null"); Class<?>[] declaredExceptions = method.getExceptionTypes(); for (Class<?> declaredException : declaredExceptions) { if (declaredException.isAssignableFrom(exceptionType)) { return true; } } return false; }
From source file:com.unboundid.scim2.common.utils.SchemaUtils.java
/** * Gets SCIM schema attributes for a class. * * @param classesProcessed a stack containing the classes processed prior * to this class. This is used for cycle detection. * @param cls the class to get the attributes for. * @return a collection of SCIM schema attributes for the class. * @throws IntrospectionException thrown if an error occurs during * Introspection./* ww w. j a v a2 s .c om*/ */ private static Collection<AttributeDefinition> getAttributes(final Stack<String> classesProcessed, final Class<?> cls) throws IntrospectionException { String className = cls.getCanonicalName(); if (!cls.isAssignableFrom(AttributeDefinition.class) && classesProcessed.contains(className)) { throw new RuntimeException("Cycles detected in Schema"); } Collection<PropertyDescriptor> propertyDescriptors = getPropertyDescriptors(cls); Collection<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals("subAttributes") && cls.isAssignableFrom(AttributeDefinition.class) && classesProcessed.contains(className)) { // Skip second nesting of subAttributes the second time around // since there is no subAttributes of subAttributes in SCIM. continue; } AttributeDefinition.Builder attributeBuilder = new AttributeDefinition.Builder(); Field field = findField(cls, propertyDescriptor.getName()); if (field == null) { continue; } Attribute schemaProperty = null; JsonProperty jsonProperty = null; if (field.isAnnotationPresent(Attribute.class)) { schemaProperty = field.getAnnotation(Attribute.class); } if (field.isAnnotationPresent(JsonProperty.class)) { jsonProperty = field.getAnnotation(JsonProperty.class); } // Only generate schema for annotated fields. if (schemaProperty == null) { continue; } addName(attributeBuilder, propertyDescriptor, jsonProperty); addDescription(attributeBuilder, schemaProperty); addCaseExact(attributeBuilder, schemaProperty); addRequired(attributeBuilder, schemaProperty); addReturned(attributeBuilder, schemaProperty); addUniqueness(attributeBuilder, schemaProperty); addReferenceTypes(attributeBuilder, schemaProperty); addMutability(attributeBuilder, schemaProperty); addMultiValued(attributeBuilder, propertyDescriptor, schemaProperty); addCanonicalValues(attributeBuilder, schemaProperty); Class propertyCls = propertyDescriptor.getPropertyType(); // if this is a multivalued attribute the real sub attribute class is the // the one specified in the annotation, not the list, set, array, etc. if ((schemaProperty.multiValueClass() != NullType.class)) { propertyCls = schemaProperty.multiValueClass(); } AttributeDefinition.Type type = getAttributeType(propertyCls); attributeBuilder.setType(type); if (type == AttributeDefinition.Type.COMPLEX) { // Add this class to the list to allow cycle detection classesProcessed.push(cls.getCanonicalName()); Collection<AttributeDefinition> subAttributes = getAttributes(classesProcessed, propertyCls); attributeBuilder .addSubAttributes(subAttributes.toArray(new AttributeDefinition[subAttributes.size()])); classesProcessed.pop(); } attributes.add(attributeBuilder.build()); } return attributes; }
From source file:cn.guoyukun.spring.utils.AopProxyUtils.java
private static void removeAdvisor(Object proxy, Class<? extends Advice> adviceClass) { if (!AopUtils.isAopProxy(proxy)) { return;/*w w w . jav a 2 s .com*/ } ProxyFactory proxyFactory = null; if (AopUtils.isJdkDynamicProxy(proxy)) { proxyFactory = findJdkDynamicProxyFactory(proxy); } if (AopUtils.isCglibProxy(proxy)) { proxyFactory = findCglibProxyFactory(proxy); } Advisor[] advisors = proxyFactory.getAdvisors(); if (advisors == null || advisors.length == 0) { return; } for (Advisor advisor : advisors) { if (adviceClass.isAssignableFrom(advisor.getAdvice().getClass())) { proxyFactory.removeAdvisor(advisor); break; } } }