List of usage examples for java.lang.reflect Modifier isAbstract
public static boolean isAbstract(int mod)
From source file:sx.blah.discord.modules.ModuleLoader.java
/** * Manually adds a module class to be considered for loading. * * @param clazz The module class.// ww w. j a v a2 s . c o m */ public static void addModuleClass(Class<? extends IModule> clazz) { if (!Modifier.isAbstract(clazz.getModifiers()) && !Modifier.isInterface(clazz.getModifiers()) && !modules.contains(clazz)) { modules.add(clazz); } }
From source file:org.interreg.docexplore.GeneralConfigPanel.java
String browseClasses(File file) { try {/*from w w w . ja va2 s . c om*/ List<Class<?>> metaDataPlugins = new LinkedList<Class<?>>(); List<Class<?>> analysisPlugins = new LinkedList<Class<?>>(); List<Class<?>> clientPlugins = new LinkedList<Class<?>>(); List<Class<?>> serverPlugins = new LinkedList<Class<?>>(); List<Class<?>> inputPlugins = new LinkedList<Class<?>>(); List<URL> urls = Startup.extractDependencies(file.getName().substring(0, file.getName().length() - 4), file.getName()); urls.add(file.toURI().toURL()); URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[] {}), this.getClass().getClassLoader()); JarFile jarFile = new JarFile(file); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (!entry.getName().endsWith(".class") || entry.getName().indexOf('$') > 0) continue; String className = entry.getName().substring(0, entry.getName().length() - 6).replace('/', '.'); Class<?> clazz = null; try { clazz = loader.loadClass(className); System.out.println("Reading " + className); } catch (NoClassDefFoundError e) { System.out.println("Couldn't read " + className); } if (clazz == null) continue; if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) continue; if (MetaDataPlugin.class.isAssignableFrom(clazz)) metaDataPlugins.add(clazz); if (AnalysisPlugin.class.isAssignableFrom(clazz)) analysisPlugins.add(clazz); if (ClientPlugin.class.isAssignableFrom(clazz)) clientPlugins.add(clazz); if (ServerPlugin.class.isAssignableFrom(clazz)) serverPlugins.add(clazz); if (InputPlugin.class.isAssignableFrom(clazz)) inputPlugins.add(clazz); } jarFile.close(); @SuppressWarnings("unchecked") Pair<String, String>[] classes = new Pair[metaDataPlugins.size() + analysisPlugins.size() + clientPlugins.size() + serverPlugins.size() + inputPlugins.size()]; if (classes.length == 0) throw new Exception("Invalid plugin (no entry points were found)."); int cnt = 0; for (Class<?> clazz : metaDataPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "MetaData plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : analysisPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Analysis plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : clientPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader client plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : serverPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader server plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : inputPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader input plugin") { public String toString() { return first + " (" + second + ")"; } }; @SuppressWarnings("unchecked") Pair<String, String> res = (Pair<String, String>) JOptionPane.showInputDialog(this, "Please select an entry point for the plugin:", "Plugin entry point", JOptionPane.QUESTION_MESSAGE, null, classes, classes[0]); if (res != null) return res.first; } catch (Throwable e) { ErrorHandler.defaultHandler.submit(e); } return null; }
From source file:com.laxser.blitz.web.impl.module.ModulesBuilderImpl.java
private boolean isCandidate(Class<?> clazz) { if (clazz.isAnnotationPresent(Ignored.class)) { if (logger.isDebugEnabled()) { logger.debug("Ignores bean definition because it's present by @Ignored : " + clazz.getName()); }/* w w w . j ava 2 s.c o m*/ return false; } if (!Modifier.isPublic(clazz.getModifiers())) { if (logger.isDebugEnabled()) { logger.debug("Ignores bean definition because it's not a public class: " + clazz.getName()); } return false; } if (Modifier.isAbstract(clazz.getModifiers())) { if (logger.isDebugEnabled()) { logger.debug("Ignores bean definition because it's a abstract class: " + clazz.getName()); } return false; } if (clazz.getDeclaringClass() != null) { if (logger.isDebugEnabled()) { logger.debug("Ignores bean definition because it's a inner class: " + clazz.getName()); } return false; } return true; }
From source file:org.datavec.api.transform.TransformProcess.java
private static ObjectMapper reinitializeMapperWithSubtypes(ObjectMapper mapper) { //Register concrete subtypes for JSON serialization List<Class<?>> classes = Arrays.<Class<?>>asList(Transform.class, Condition.class, Filter.class, IReducer.class); List<String> classNames = new ArrayList<>(6); for (Class<?> c : classes) classNames.add(c.getName());//from w ww . j a v a 2 s . c o m // First: scan the classpath and find all instances of the 'baseClasses' classes if (subtypesClassCache == null) { List<Class<?>> interfaces = Arrays.<Class<?>>asList(Transform.class, Condition.class, Filter.class, IReducer.class); List<Class<?>> classesList = Arrays.<Class<?>>asList(); Collection<URL> urls = ClasspathHelper.forClassLoader(); List<URL> scanUrls = new ArrayList<>(); for (URL u : urls) { String path = u.getPath(); if (!path.matches(".*/jre/lib/.*jar")) { //Skip JRE/JDK JARs scanUrls.add(u); } } Reflections reflections = new Reflections( new ConfigurationBuilder().filterInputsBy(new FilterBuilder().exclude("^(?!.*\\.class$).*$") //Consider only .class files (to avoid debug messages etc. on .dlls, etc //Exclude the following: the assumption here is that no custom functionality will ever be present // under these package name prefixes. .exclude("^org.nd4j.*").exclude("^org.bytedeco.*") //JavaCPP .exclude("^com.fasterxml.*")//Jackson .exclude("^org.apache.*") //Apache commons, Spark, log4j etc .exclude("^org.projectlombok.*").exclude("^com.twelvemonkeys.*").exclude("^org.joda.*") .exclude("^org.slf4j.*").exclude("^com.google.*").exclude("^org.reflections.*") .exclude("^ch.qos.*") //Logback ).addUrls(scanUrls).setScanners(new DataVecSubTypesScanner(interfaces, classesList))); org.reflections.Store store = reflections.getStore(); Iterable<String> subtypesByName = store.getAll(DataVecSubTypesScanner.class.getSimpleName(), classNames); Set<? extends Class<?>> subtypeClasses = Sets.newHashSet(ReflectionUtils.forNames(subtypesByName)); subtypesClassCache = new HashSet<>(); for (Class<?> c : subtypeClasses) { if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { //log.info("Skipping abstract/interface: {}",c); continue; } subtypesClassCache.add(c); } } //Second: get all currently registered subtypes for this mapper Set<Class<?>> registeredSubtypes = new HashSet<>(); for (Class<?> c : classes) { AnnotatedClass ac = AnnotatedClass.construct(c, mapper.getSerializationConfig().getAnnotationIntrospector(), null); Collection<NamedType> types = mapper.getSubtypeResolver().collectAndResolveSubtypes(ac, mapper.getSerializationConfig(), mapper.getSerializationConfig().getAnnotationIntrospector()); for (NamedType nt : types) { registeredSubtypes.add(nt.getType()); } } //Third: register all _concrete_ subtypes that are not already registered List<NamedType> toRegister = new ArrayList<>(); for (Class<?> c : subtypesClassCache) { //Check if it's concrete or abstract... if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { //log.info("Skipping abstract/interface: {}",c); continue; } if (!registeredSubtypes.contains(c)) { String name; if (ClassUtils.isInnerClass(c)) { Class<?> c2 = c.getDeclaringClass(); name = c2.getSimpleName() + "$" + c.getSimpleName(); } else { name = c.getSimpleName(); } toRegister.add(new NamedType(c, name)); if (log.isDebugEnabled()) { for (Class<?> baseClass : classes) { if (baseClass.isAssignableFrom(c)) { log.debug("Registering class for JSON serialization: {} as subtype of {}", c.getName(), baseClass.getName()); break; } } } } } mapper.registerSubtypes(toRegister.toArray(new NamedType[toRegister.size()])); //Recreate the mapper (via copy), as mapper won't use registered subtypes after first use mapper = mapper.copy(); return mapper; }
From source file:com.yahoo.elide.core.EntityDictionary.java
/** * Find an arbitrary method./*from w ww. j a va 2s . co m*/ * * @param entityClass the entity class * @param name the name * @param paramClass the param class * @return method method * @throws NoSuchMethodException the no such method exception */ public static Method findMethod(Class<?> entityClass, String name, Class<?>... paramClass) throws NoSuchMethodException { Method m = entityClass.getMethod(name, paramClass); int modifiers = m.getModifiers(); if (Modifier.isAbstract(modifiers) || (m.isAnnotationPresent(Transient.class) && !m.isAnnotationPresent(ComputedAttribute.class))) { throw new NoSuchMethodException(name); } return m; }
From source file:com.azure.webapi.MobileServiceClient.java
/** * Validates the class has an id property defined * /* w w w . j a v a2s.com*/ * @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:ca.sqlpower.object.annotation.SPAnnotationProcessor.java
/** * Generates the Java source file for an {@link SPPersisterHelper} class * that is to be used by a session {@link SPPersister} or workspace * persister listener. This generated persister helper class should deal * with creating new objects and applying persisted properties to a given * {@link SPObject}, or persisting objects and properties from an * {@link SPObject} to an {@link SPPersister}. * // w w w .ja v a2 s .co m * @param visitedClass * The {@link SPObject} class that is being visited by the * annotation processor. * @param constructorImports * The {@link Set} of imports that the generated persister helper * requires for calling the {@link Constructor} annotated * constructor. * @param constructorParameters * The {@link List} of {@link ConstructorParameterObject}s that * contain information about what the parameter should be used * for. * @param propertiesToAccess * The {@link Map} of getter method names of persistable * properties to its property type. * @param accessorAdditionalInfo * The {@link Multimap} of getter methods mapped to additional * properties a session {@link SPPersister} requires to convert * the getter's returned value from a complex to basic * persistable type. * @param mutatorImports * The {@link Multimap} of setter methods to imports that the * generated persister helper requires for calling the * {@link Mutator} annotated setters. * @param propertiesToMutate * The {@link Map} of setter method names of persistable * properties to its property type. * @param mutatorExtraParameters * The {@link Multimap} of setter methods mapped to each of its * extra parameters (second parameter and onwards). * @param mutatorThrownTypes * The {@link Multimap} of {@link Exception}s thrown by each * persistable property setter. * @param propertiesToPersistOnlyIfNonNull * The {@link Set} of persistable properties that can only be * persisted if its value is not null. */ private void generatePersisterHelperFile(Class<? extends SPObject> visitedClass, Set<String> constructorImports, List<ConstructorParameterObject> constructorParameters, Map<String, Class<?>> propertiesToAccess, Multimap<String, String> accessorAdditionalInfo, Multimap<String, String> mutatorImports, Map<String, Class<?>> propertiesToMutate, Multimap<String, MutatorParameterObject> mutatorExtraParameters, Multimap<String, Class<? extends Exception>> mutatorThrownTypes, Set<String> propertiesToPersistOnlyIfNonNull) { try { final String helperPackage = visitedClass.getPackage().getName() + "." + PersisterHelperFinder.GENERATED_PACKAGE_NAME; final String simpleClassName = visitedClass.getSimpleName() + "PersisterHelper"; final Class<?> superclass = visitedClass.getSuperclass(); int tabs = 0; Filer f = environment.getFiler(); PrintWriter pw = new PrintWriter( f.createSourceFile(helperPackage + "." + simpleClassName).openOutputStream()); tabs++; final String commitObjectMethod = generateCommitObjectMethod(visitedClass, constructorParameters, tabs); final String commitPropertyMethod = generateCommitPropertyMethod(visitedClass, propertiesToMutate, mutatorExtraParameters, mutatorThrownTypes, tabs); final String findPropertyMethod = generateFindPropertyMethod(visitedClass, propertiesToAccess, accessorAdditionalInfo, tabs); final String persistObjectMethod = generatePersistObjectMethod(visitedClass, constructorParameters, propertiesToAccess, propertiesToPersistOnlyIfNonNull, tabs); final String PersistObjectMethodHelper = generatePersistObjectMethodHelper(visitedClass, propertiesToAccess, propertiesToMutate, propertiesToPersistOnlyIfNonNull, tabs); final String getPersistedPropertiesMethod = generateGetPersistedPropertyListMethod(visitedClass, propertiesToMutate, tabs); tabs--; if (superclass == Object.class) { importedClassNames.add(AbstractSPPersisterHelper.class.getName()); } else { importedClassNames.add(PersisterHelperFinder.getPersisterHelperClassName(superclass.getName())); } final String imports = generateImports(visitedClass, constructorImports, mutatorImports); pw.print(generateWarning()); pw.print("\n"); pw.print(generateLicense()); pw.print("\n"); pw.print("package " + helperPackage + ";\n"); pw.print("\n"); pw.print(imports); pw.print("\n"); if (superclass == Object.class) { pw.print(String.format("public class %s extends %s<%s> {\n", simpleClassName, AbstractSPPersisterHelper.class.getSimpleName(), visitedClass.getSimpleName())); } else if (Modifier.isAbstract(superclass.getModifiers())) { pw.print(String.format("public class %s extends %s<%s> {\n", simpleClassName, superclass.getSimpleName() + "PersisterHelper", visitedClass.getSimpleName())); } else { pw.print(String.format("public class %s extends %s {\n", simpleClassName, superclass.getSimpleName() + "PersisterHelper")); } pw.print("\n"); pw.print(commitObjectMethod); pw.print("\n"); pw.print(commitPropertyMethod); pw.print("\n"); pw.print(findPropertyMethod); pw.print("\n"); pw.print(persistObjectMethod); pw.print("\n"); pw.print(PersistObjectMethodHelper); pw.print("\n"); pw.print(getPersistedPropertiesMethod); pw.print("\n"); pw.print("}\n"); pw.close(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.apache.openjpa.persistence.jdbc.XMLPersistenceMappingParser.java
/** * Parse discriminator-value./*from w w w . j a v a 2 s.c o m*/ */ private void endDiscriminatorValue() { String val = currentText(); if (StringUtils.isEmpty(val)) return; ClassMapping cm = (ClassMapping) currentElement(); cm.getDiscriminator().getMappingInfo().setValue(val); if (Modifier.isAbstract(cm.getDescribedType().getModifiers()) && getLog().isInfoEnabled()) { getLog().info(_loc.get("discriminator-on-abstract-class", cm.getDescribedType().getName())); } }
From source file:org.apache.jackrabbit.ocm.manager.objectconverter.impl.ObjectConverterImpl.java
/** * @see org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter#getObject(javax.jcr.Session, * java.lang.Class, java.lang.String) *///from w w w . j a v a 2 s . c om public Object getObject(Session session, Class clazz, String path) { try { if (!session.itemExists(path)) { return null; } if (requestObjectCache.isCached(path)) { return requestObjectCache.getObject(path); } ClassDescriptor classDescriptor = getClassDescriptor(clazz); checkNodeType(session, classDescriptor); Node node = (Node) session.getItem(path); if (!classDescriptor.isInterface()) { node = getActualNode(session, node); checkCompatiblePrimaryNodeTypes(session, node, classDescriptor, true); } ClassDescriptor alternativeDescriptor = null; if (classDescriptor.usesNodeTypePerHierarchyStrategy()) { if (node.hasProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY)) { String className = node.getProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY) .getValue().getString(); alternativeDescriptor = getClassDescriptor(ReflectionUtils.forName(className)); } } else { if (classDescriptor.usesNodeTypePerConcreteClassStrategy()) { String nodeType = node.getPrimaryNodeType().getName(); if (!nodeType.equals(classDescriptor.getJcrType())) { alternativeDescriptor = classDescriptor.getDescendantClassDescriptor(nodeType); // in case we an alternative could not be found by walking // the class descriptor hierarchy, check whether we would // have a descriptor for the node type directly (which // may the case if the class descriptor hierarchy is // incomplete due to missing configuration. See JCR-1145 // for details. if (alternativeDescriptor == null) { alternativeDescriptor = mapper.getClassDescriptorByNodeType(nodeType); } } } } // if we have an alternative class descriptor, check whether its // extends (or is the same) as the requested class. if (alternativeDescriptor != null) { Class alternativeClazz = ReflectionUtils.forName(alternativeDescriptor.getClassName()); if (clazz.isAssignableFrom(alternativeClazz)) { clazz = alternativeClazz; classDescriptor = alternativeDescriptor; } } // ensure class is concrete (neither interface nor abstract) if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) { throw new JcrMappingException("Cannot instantiate non-concrete class " + clazz.getName() + " for node " + path + " of type " + node.getPrimaryNodeType().getName()); } Object object = ReflectionUtils.newInstance(classDescriptor.getClassName()); if (!requestObjectCache.isCached(path)) { requestObjectCache.cache(path, object); } simpleFieldsHelp.retrieveSimpleFields(session, classDescriptor, node, object); retrieveBeanFields(session, classDescriptor, node, path, object, false); retrieveCollectionFields(session, classDescriptor, node, object, false); return object; } catch (PathNotFoundException pnfe) { // HINT should never get here throw new ObjectContentManagerException("Impossible to get the object at " + path, pnfe); } catch (RepositoryException re) { throw new org.apache.jackrabbit.ocm.exception.RepositoryException( "Impossible to get the object at " + path, re); } }