List of usage examples for java.lang Class isInterface
@HotSpotIntrinsicCandidate public native boolean isInterface();
From source file:org.ebayopensource.twin.ElementImpl.java
public boolean is(Class<? extends Element> pattern) { if (pattern.isInterface()) for (Class<?> iface : pattern.getInterfaces()) { if (iface == ControlPattern.class) return controlPatterns.contains(pattern); else if (iface == ControlType.class) return controlType == pattern; }/* ww w.ja v a 2 s.c om*/ // if it's not a control type or control pattern, return instanceof return pattern.isInstance(this); }
From source file:cat.albirar.framework.dynabean.impl.DynaBeanDescriptor.java
/** * Constructor with the type to implement to get the information. * @param factory The factory to work with * @param typeToImplement the {@link Class} type to implement. * @throws IllegalArgumentException If {@code typeToImplement} is null or isn't an interface *//* w w w .j a v a 2 s . c o m*/ public DynaBeanDescriptor(IDynaBeanImplementationFactory factory, Class<T> typeToImplement) { this(factory); DynaBeanPropertyDescriptor propDesc; StringBuilder stb; String s; if (typeToImplement == null || typeToImplement.isInterface() == false) { if (typeToImplement == null) { logger.error("The type to implement is required"); throw new IllegalArgumentException("The type to implement is required"); } // Only interfaces logger.error("DynaBean can only implement interfaces. '" + typeToImplement.getName() + "' is not an interface"); throw new IllegalArgumentException("DynaBean can only implement interfaces. '" + typeToImplement.getName() + "' is not an interface"); } implementedType = typeToImplement; if (logger.isDebugEnabled()) { logger.debug("Working for implementing the type '".concat(typeToImplement.getName()).concat("'")); } // Prepare the properties list for (Method method : typeToImplement.getMethods()) { if (isPropertyMethod(method.getName()) && isCorrectProperty(method)) { if ((propDesc = getPropertyByMethodName(method.getName())) == null) { // Put them! propDesc = new DynaBeanPropertyDescriptor(); propDesc.propertyName = fromMethodToPropertyName(method.getName()); propDesc.propertyPath = implementedType.getName().concat(".").concat(propDesc.propertyName); if (logger.isDebugEnabled()) { logger.debug("Working on property '".concat(implementedType.getName()).concat(".") .concat(propDesc.getPropertyName())); } if (isGetter(method.getName())) { propDesc.getterMethod = method; } else { propDesc.setterMethod = method; } resolvePropertyComponentType(propDesc); resolvePropertyEditorForProperty(propDesc); resolvePropertyCloneMethod(propDesc); properties.put(propDesc.getPropertyName(), propDesc); } else { if (isGetter(method.getName())) { propDesc.getterMethod = method; } else { propDesc.setterMethod = method; } } } else { if (!isPropertyMethod(method.getName())) { if (logger.isInfoEnabled()) { logger.info(String.format(PATTERN_IGNORING_PROPERTIES, implementedType.getName(), method.getName(), " is not a property method")); } } if (!isCorrectProperty(method)) { if (logger.isWarnEnabled()) { logger.warn(String.format(PATTERN_IGNORING_PROPERTIES, implementedType.getName(), method.getName(), " is an INVALID PROPERTY METHOD")); } } } } // Check that at least one property is found Assert.isTrue(!properties.isEmpty(), "The model '" + implementedType.getName() + "' doesn't defines a valid model, doesn't have any valid property"); // Check value coherence for (DynaBeanPropertyDescriptor property : properties.values()) { // Check type return and set equals if (property.isRW()) { // All two methods should to have the same type Assert.isTrue( property.getterMethod.getReturnType().equals(property.setterMethod.getParameterTypes()[0]), String.format( "The set and get values of the property '%s' at '%s' model ARE DIFFERENTS. This model is invalid", property.propertyName, implementedType.getName())); } } // The descriptor have all the properties // Prepare the string pattern and test annotations stb = new StringBuilder(); stb.append(implementedType.getSimpleName()).append(" ["); s = ""; for (String name : getPropertyNames()) { // Test annotations processAnnotations(properties.get(name)); // Add the property to the 'toString' pattern stb.append(s).append(name).append("=%s"); s = ", "; } // Change the last element (",") by "]" stb.append("]"); patternForToString = stb.toString(); if (logger.isDebugEnabled()) { logger.debug("Pattern string for '".concat(implementedType.getClass().getName()).concat("': ") .concat(patternForToString)); } validDescriptor = true; }
From source file:org.gwtspringhibernate.reference.rlogman.spring.GwtServiceExporter.java
/** * Only called from isImplementedInterface(). *///from ww w . ja va2 s .c o m private boolean isImplementedRemoteServiceInterfaceRecursive(String intfName, Class intfToCheck) { assert (intfToCheck.isInterface()); if (intfToCheck.getName().equals(intfName)) { // The name is right, but we also verify that it is assignable to // RemoteService. // if (RemoteService.class.isAssignableFrom(intfToCheck)) { return true; } else { return false; } } Class[] intfs = intfToCheck.getInterfaces(); for (int i = 0; i < intfs.length; i++) { Class intf = intfs[i]; if (isImplementedRemoteServiceInterfaceRecursive(intfName, intf)) { return true; } } return false; }
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
private static void mapComplexTypes(List<APITypeModel> typeModels, Field fields[], boolean onlyConsumeField) { //Should strip duplicate types Set<String> typesInList = new HashSet<>(); typeModels.forEach(type -> {/*from ww w. j a v a2 s . com*/ typesInList.add(type.getName()); }); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); for (Field field : fields) { boolean capture = true; if (onlyConsumeField) { ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class); if (consumeField == null) { capture = false; } } if (capture) { Class fieldClass = field.getType(); DataType dataType = (DataType) field.getAnnotation(DataType.class); if (dataType != null) { fieldClass = dataType.value(); } if (ReflectionUtil.isComplexClass(fieldClass)) { APITypeModel typeModel = new APITypeModel(); typeModel.setName(fieldClass.getSimpleName()); APIDescription aPIDescription = (APIDescription) fieldClass.getAnnotation(APIDescription.class); if (aPIDescription != null) { typeModel.setDescription(aPIDescription.value()); } Set<String> fieldList = mapValueField(typeModel.getFields(), fieldClass.getDeclaredFields(), onlyConsumeField); if (fieldClass.isEnum()) { typeModel.setObject(Arrays.toString(fieldClass.getEnumConstants())); } else { if (fieldClass.isInterface() == false) { try { typeModel.setObject(objectMapper.writeValueAsString(fieldClass.newInstance())); String cleanUpJson = StringProcessor.stripeFieldJSON(typeModel.getObject(), fieldList); typeModel.setObject(cleanUpJson); } catch (InstantiationException | IllegalAccessException | JsonProcessingException ex) { log.log(Level.WARNING, "Unable to process/map complex field: " + fieldClass.getSimpleName(), ex); typeModel.setObject("{ Unable to view }"); } mapComplexTypes(typeModels, fieldClass.getDeclaredFields(), onlyConsumeField); } } typeModels.add(typeModel); typesInList.add(typeModel.getName()); } } } }
From source file:fr.exanpe.tapestry.tldgen.taglib.builder.StructureBuilder.java
/** * Builds the output taglib structure/*w ww .java 2s . co m*/ * * @param rootPackage the root package to look the components for * @param supportedPackages all sub packages to scan * @param urls the urls used to scan the packages * @return the structure containing the information on the taglib to generate * @throws MojoExecutionException if any unexpected error occurs */ public Taglib build(String rootPackage, String[] supportedPackages, URL[] urls) throws MojoExecutionException { Taglib taglib = new Taglib(); log.debug("Creating taglib object model..."); for (String subPackage : supportedPackages) { String pkgname = rootPackage + "." + subPackage; log.debug("Processing taglib for full package named : " + pkgname); Reflections reflections = new Reflections(new ConfigurationBuilder() .filterInputsBy(new FilterBuilder.Include(FilterBuilder.prefix(pkgname))).setUrls(urls) .setScanners(new TypesScanner())); Store store = reflections.getStore(); // Return classes anaylised by TypeScanner Multimap<String, String> classes = store.getStoreMap().values().iterator().next(); log.debug(String.format("%s classes to analyse for %s package...", classes.keySet().size(), pkgname)); // Loop on found classes for (final String s : classes.keySet()) { Class<?> c; try { log.debug(String.format("Load class %s into classloader", s)); c = Thread.currentThread().getContextClassLoader().loadClass(s); } catch (ClassNotFoundException e) { // should not happen as it has just been parsed by Reflection... log.error(e); throw new MojoExecutionException("Class loader internal error for class :" + s, e); } if (!c.isAnnotation() && !c.isAnonymousClass() && !c.isEnum() && !c.isInterface() && !c.isLocalClass() && !c.isMemberClass() && !c.isSynthetic() && !Modifier.isAbstract(c.getModifiers())) { log.debug("Processing Tag : " + c.getName()); Tag tag = buildTagFromClass(rootPackage, c); taglib.getTags().add(tag); } } } log.debug("Taglib object model completed"); return taglib; }
From source file:com.kugou.limos.config.AbstractInterfaceConfig.java
protected void checkInterfaceAndMethods(Class<?> interfaceClass, List<MethodConfig> methods) { // ??//w ww.j av a 2 s. c o m if (interfaceClass == null) { throw new IllegalStateException("interface not allow null!"); } // ?? if (!interfaceClass.isInterface()) { throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!"); } // ?? if (methods != null && methods.size() > 0) { for (MethodConfig methodBean : methods) { String methodName = methodBean.getName(); if (methodName == null || methodName.length() == 0) { throw new IllegalStateException( "<dubbo:method> name attribute is required! Please check: <dubbo:service interface=\"" + interfaceClass.getName() + "\" ... ><dubbo:method name=\"\" ... /></<dubbo:reference>"); } boolean hasMethod = false; for (java.lang.reflect.Method method : interfaceClass.getMethods()) { if (method.getName().equals(methodName)) { hasMethod = true; break; } } if (!hasMethod) { throw new IllegalStateException( "The interface " + interfaceClass.getName() + " not found method " + methodName); } } } }
From source file:org.gradle.model.internal.manage.schema.extract.StructStrategy.java
public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext, final ModelSchemaCache cache) { ModelType<R> type = extractionContext.getType(); Class<? super R> clazz = type.getRawClass(); if (clazz.isAnnotationPresent(Managed.class)) { validateType(type, extractionContext); Iterable<Method> methods = Arrays.asList(clazz.getMethods()); if (!clazz.isInterface()) { methods = filterIgnoredMethods(methods); }/*from w ww . j a v a 2 s . c om*/ ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods, new Function<Method, String>() { public String apply(Method method) { return method.getName(); } }); ensureNoOverloadedMethods(extractionContext, methodsByName); List<ModelProperty<?>> properties = Lists.newLinkedList(); List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length); ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering(); for (String methodName : methodsByName.keySet()) { if (methodName.startsWith("get") && !methodName.equals("get")) { ImmutableList<Method> getterMethods = methodsByName.get(methodName); // The overload check earlier verified that all methods for are equivalent for our purposes // So, taking the first one with the most specialized return type is fine. Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods); boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers()); if (sampleMethod.getParameterTypes().length != 0) { throw invalidMethod(extractionContext, "getter methods cannot take parameters", sampleMethod); } Character getterPropertyNameFirstChar = methodName.charAt(3); if (!Character.isUpperCase(getterPropertyNameFirstChar)) { throw invalidMethod(extractionContext, "the 4th character of the getter method name must be an uppercase character", sampleMethod); } ModelType<?> returnType = ModelType.returnType(sampleMethod); String propertyNameCapitalized = methodName.substring(3); String propertyName = StringUtils.uncapitalize(propertyNameCapitalized); String setterName = "set" + propertyNameCapitalized; ImmutableList<Method> setterMethods = methodsByName.get(setterName); boolean isWritable = !setterMethods.isEmpty(); if (isWritable) { Method setter = setterMethods.get(0); if (!abstractGetter) { throw invalidMethod(extractionContext, "setters are not allowed for non-abstract getters", setter); } validateSetter(extractionContext, returnType, setter); handled.addAll(setterMethods); } if (abstractGetter) { ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() { public ModelType<?> apply(Method input) { return ModelType.of(input.getDeclaringClass()); } })); boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() { public boolean apply(Method input) { return input.getAnnotation(Unmanaged.class) != null; } }); properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses, unmanaged)); } handled.addAll(getterMethods); } } Iterable<Method> notHandled = Iterables.filter(methodsByName.values(), Predicates.not(Predicates.in(handled))); // TODO - should call out valid getters without setters if (!Iterables.isEmpty(notHandled)) { throw invalidMethods(extractionContext, "only paired getter/setter methods are supported", notHandled); } Class<R> concreteClass = type.getConcreteClass(); Class<? extends R> implClass = classGenerator.generate(concreteClass); final ModelStructSchema<R> schema = ModelSchema.struct(type, properties, implClass); extractionContext.addValidator(new Action<ModelSchemaExtractionContext<R>>() { @Override public void execute(ModelSchemaExtractionContext<R> validatorModelSchemaExtractionContext) { ensureCanBeInstantiated(extractionContext, schema); } }); Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties, new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() { public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) { return toPropertyExtractionContext(extractionContext, property, cache); } }); return new ModelSchemaExtractionResult<R>(schema, propertyDependencies); } else { return null; } }
From source file:com.azure.webapi.MobileServiceClient.java
/** * Validates the class has an id property defined * /*from w ww . j a v a 2 s .co m*/ * @param clazz */ private <E> void validateClass(Class<E> clazz) { if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) { throw new IllegalArgumentException( "The class type used for creating a MobileServiceTable must be a concrete class"); } int idPropertyCount = 0; for (Field field : clazz.getDeclaredFields()) { SerializedName serializedName = field.getAnnotation(SerializedName.class); if (serializedName != null) { if (serializedName.value().equalsIgnoreCase("id")) { idPropertyCount++; } } else { if (field.getName().equalsIgnoreCase("id")) { idPropertyCount++; } } } if (idPropertyCount != 1) { throw new IllegalArgumentException( "The class representing the MobileServiceTable must have a single id property defined"); } }
From source file:info.magnolia.jcr.node2bean.impl.Node2BeanTransformerImpl.java
/** * Creates collection from map. Collection type depends on passed class parameter. If passed class parameter is * interface, then default implementation will be used for creating collection.<br/> * By default/*from www . j av a2 s.c o m*/ * <ul> * <li>{@link LinkedList} is used for creating List and Queue collections.</li> * <li>{@link HashSet} is used for creating Set collection.</li> * </ul> * If passed class parameter is an implementation of any collection type, then this method will create * this implementation and returns it. * * @param map a map which values will be converted to a collection * @param clazz collection type * @return Collection of elements or null. */ protected Collection<?> createCollectionFromMap(Map<?, ?> map, Class<?> clazz) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Collection<?> collection = null; Constructor<?> constructor = null; if (clazz.isInterface()) { // class is an interface, we need to decide which implementation of interface we will use if (List.class.isAssignableFrom(clazz)) { constructor = defaultListImpl.getConstructor(Collection.class); } else if (clazz.isAssignableFrom(Queue.class)) { constructor = defaultQueueImpl.getConstructor(Collection.class); } else if (Set.class.isAssignableFrom(clazz)) { constructor = defaultSetImpl.getConstructor(Collection.class); } } else { if (Collection.class.isAssignableFrom(clazz)) { constructor = clazz.getConstructor(Collection.class); } } if (constructor != null) { collection = (Collection<?>) constructor.newInstance(map.values()); } return collection; }