List of usage examples for java.lang Class getModifiers
@HotSpotIntrinsicCandidate public native int getModifiers();
From source file:io.smartspaces.workbench.project.test.JunitTestClassDetector.java
/** * Is the class a JUnit test class?//from w w w . j av a 2 s.com * * @param potentialTestClass * the class to test * @param log * the logger to use * * @return {@code true} if the class is testable and can be instantiated */ private boolean isTestClass(Class<?> potentialTestClass, Log log) { if (potentialTestClass.isInterface() || !classHasPublicConstructor(potentialTestClass, log)) { return false; } // Do not attempt to run tests on abstract test classes. if (Modifier.isAbstract(potentialTestClass.getModifiers())) { return false; } for (Method method : potentialTestClass.getMethods()) { if (method.isAnnotationPresent(Test.class)) { // No need to check any more if we have 1 return true; } } return false; }
From source file:alluxio.cli.fs.FileSystemShellUtilsTest.java
@Test public void loadCommands() { Map<String, Command> map = FileSystemShellUtils.loadCommands(mFileSystem); String pkgName = Command.class.getPackage().getName(); Reflections reflections = new Reflections(pkgName); Set<Class<? extends Command>> cmdSet = reflections.getSubTypesOf(Command.class); for (Map.Entry<String, Command> entry : map.entrySet()) { Assert.assertEquals(entry.getValue().getCommandName(), entry.getKey()); Assert.assertEquals(cmdSet.contains(entry.getValue().getClass()), true); }/*ww w .j a va2s. c o m*/ int expectSize = 0; for (Class<? extends Command> cls : cmdSet) { if (cls.getPackage().getName().equals(FileSystemShell.class.getPackage().getName() + ".command") && !Modifier.isAbstract(cls.getModifiers())) { expectSize++; } } Assert.assertEquals(expectSize, map.size()); }
From source file:org.apache.syncope.client.console.init.ClassPathScanImplementationLookup.java
@SuppressWarnings("unchecked") public void load() { pages = new ArrayList<>(); previewers = new ArrayList<>(); extPages = new ArrayList<>(); extWidgets = new ArrayList<>(); ssoLoginFormPanels = new ArrayList<>(); reportletConfs = new HashMap<>(); accountRuleConfs = new HashMap<>(); passwordRuleConfs = new HashMap<>(); pullCorrelationRuleConfs = new HashMap<>(); ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider( false);// w ww .j a v a 2 s . c om scanner.addIncludeFilter(new AssignableTypeFilter(BasePage.class)); scanner.addIncludeFilter(new AssignableTypeFilter(AbstractBinaryPreviewer.class)); scanner.addIncludeFilter(new AssignableTypeFilter(BaseExtPage.class)); scanner.addIncludeFilter(new AssignableTypeFilter(BaseExtWidget.class)); scanner.addIncludeFilter(new AssignableTypeFilter(SSOLoginFormPanel.class)); scanner.addIncludeFilter(new AssignableTypeFilter(ReportletConf.class)); scanner.addIncludeFilter(new AssignableTypeFilter(AccountRuleConf.class)); scanner.addIncludeFilter(new AssignableTypeFilter(PasswordRuleConf.class)); scanner.addIncludeFilter(new AssignableTypeFilter(PullCorrelationRuleConf.class)); scanner.findCandidateComponents(getBasePackage()).forEach(bd -> { try { Class<?> clazz = ClassUtils.resolveClassName(bd.getBeanClassName(), ClassUtils.getDefaultClassLoader()); boolean isAbsractClazz = Modifier.isAbstract(clazz.getModifiers()); if (!isAbsractClazz) { if (BaseExtPage.class.isAssignableFrom(clazz)) { if (clazz.isAnnotationPresent(ExtPage.class)) { extPages.add((Class<? extends BaseExtPage>) clazz); } else { LOG.error("Could not find annotation {} in {}, ignoring", ExtPage.class.getName(), clazz.getName()); } } else if (BaseExtWidget.class.isAssignableFrom(clazz)) { if (clazz.isAnnotationPresent(ExtWidget.class)) { extWidgets.add((Class<? extends BaseExtWidget>) clazz); } else { LOG.error("Could not find annotation {} in {}, ignoring", ExtWidget.class.getName(), clazz.getName()); } } else if (BasePage.class.isAssignableFrom(clazz)) { pages.add((Class<? extends BasePage>) clazz); } else if (AbstractBinaryPreviewer.class.isAssignableFrom(clazz)) { previewers.add((Class<? extends AbstractBinaryPreviewer>) clazz); } else if (SSOLoginFormPanel.class.isAssignableFrom(clazz)) { ssoLoginFormPanels.add((Class<? extends SSOLoginFormPanel>) clazz); } else if (ReportletConf.class.isAssignableFrom(clazz)) { reportletConfs.put(clazz.getName(), (Class<? extends ReportletConf>) clazz); } else if (AccountRuleConf.class.isAssignableFrom(clazz)) { accountRuleConfs.put(clazz.getName(), (Class<? extends AccountRuleConf>) clazz); } else if (PasswordRuleConf.class.isAssignableFrom(clazz)) { passwordRuleConfs.put(clazz.getName(), (Class<? extends PasswordRuleConf>) clazz); } else if (PullCorrelationRuleConf.class.isAssignableFrom(clazz)) { pullCorrelationRuleConfs.put(clazz.getName(), (Class<? extends PullCorrelationRuleConf>) clazz); } } } catch (Throwable t) { LOG.warn("Could not inspect class {}", bd.getBeanClassName(), t); } }); pages = Collections.unmodifiableList(pages); previewers = Collections.unmodifiableList(previewers); Collections.sort(extPages, (o1, o2) -> ObjectUtils.compare(o1.getAnnotation(ExtPage.class).priority(), o2.getAnnotation(ExtPage.class).priority())); extPages = Collections.unmodifiableList(extPages); Collections.sort(extWidgets, (o1, o2) -> ObjectUtils.compare(o1.getAnnotation(ExtWidget.class).priority(), o2.getAnnotation(ExtWidget.class).priority())); extWidgets = Collections.unmodifiableList(extWidgets); ssoLoginFormPanels = Collections.unmodifiableList(ssoLoginFormPanels); reportletConfs = Collections.unmodifiableMap(reportletConfs); accountRuleConfs = Collections.unmodifiableMap(accountRuleConfs); passwordRuleConfs = Collections.unmodifiableMap(passwordRuleConfs); pullCorrelationRuleConfs = Collections.unmodifiableMap(pullCorrelationRuleConfs); LOG.debug("Binary previewers found: {}", previewers); LOG.debug("Extension pages found: {}", extPages); LOG.debug("Extension widgets found: {}", extWidgets); LOG.debug("SSO Login pages found: {}", ssoLoginFormPanels); LOG.debug("Reportlet configurations found: {}", reportletConfs); LOG.debug("Account Rule configurations found: {}", accountRuleConfs); LOG.debug("Password Rule configurations found: {}", passwordRuleConfs); LOG.debug("Pull Correlation Rule configurations found: {}", pullCorrelationRuleConfs); }
From source file:com.px100systems.data.core.DatabaseStorage.java
@Override @SuppressWarnings("unchecked") public void afterPropertiesSet() throws Exception { if (tenantLoader != null) tenantLoader.setDatabase(this); configuredEntities = new HashMap<String, Class<? extends Entity>>(); try {/*from ww w. jav a2 s . c o m*/ ClassPath cp = ClassPath.from(getClass().getClassLoader()); for (String p : baseEntityPackages) for (ClassPath.ClassInfo cli : cp.getTopLevelClassesRecursive(p)) { Class<?> eClass = Class.forName(cli.getName()); if (!Modifier.isAbstract(eClass.getModifiers()) && Entity.class.isAssignableFrom(eClass)) { Class<? extends Entity> entityClass = (Class<? extends Entity>) eClass; String name = entityClass.getSimpleName(); Class<? extends Entity> cls = configuredEntities.get(name); if (cls != null) { if (cls.getName().equals(entityClass.getName())) continue; throw new RuntimeException("Duplicate entities in different packages: " + name); } configuredEntities.put(name, entityClass); SerializationDefinition.register(entityClass); } } } catch (Exception e1) { throw new RuntimeException(e1); } SerializationDefinition.lock(); runtimeStorage.getProvider().start(); List<BaseTenantConfig> tenants = new ArrayList<BaseTenantConfig>(); if (tenantLoader != null) tenants = tenantLoader.load(); List<EntityInfo> entities = new ArrayList<>(); for (Class<? extends Entity> entityClass : getConfiguredEntities().values()) { Map<String, Class<?>> indexes = Entity.indexes(entityClass); List<CompoundIndexDescriptor> compoundIndexes = Entity.compoundIndexes(entityClass); if (tenants.isEmpty()) entities.add(new EntityInfo(entityClass, 0, Entity.unitFromClass(entityClass, 0), indexes, compoundIndexes)); else for (BaseTenantConfig tenant : tenants) entities.add(new EntityInfo(entityClass, tenant.getId(), Entity.unitFromClass(entityClass, tenant.getId()), indexes, compoundIndexes)); } init(entities, initializer != null); if (initializer != null) { initializer.initialize(new Transaction(this, 0)); log.info("Initialized the database"); } }
From source file:org.unitils.mock.core.MockFactory.java
public Mock<?> createChainedMock(MatchingInvocation matchingInvocation) { Object matchingProxy = matchingInvocation.getProxy(); Map<Method, Mock<?>> chainedMocksForProxy = chainedMocks.get(matchingProxy); if (chainedMocksForProxy == null) { chainedMocksForProxy = new HashMap<Method, Mock<?>>(); chainedMocks.put(matchingProxy, chainedMocksForProxy); }/*from w w w . j a v a 2 s .co m*/ Method method = matchingInvocation.getMethod(); Mock<?> chainedMock = chainedMocksForProxy.get(method); if (chainedMock != null) { return chainedMock; } String name = matchingInvocation.getInnerMockName(); Class<?> mockedType = matchingInvocation.getReturnType(); if (mockedType == Void.TYPE) { return null; } if (mockedType.isPrimitive() || mockedType.isArray() || Modifier.isFinal(mockedType.getModifiers())) { if (logger.isDebugEnabled()) { logger.debug("Unable to create chained mock " + name + " for return type +" + mockedType + ". Chaining not supported for primitive, arrays or final types, returning null."); } return null; } try { chainedMock = createMockObject(name, mockedType, true); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Unable to create chained mock " + name + " for return type +" + mockedType + ". Chaining not supported, returning null."); } return null; } chainedMocksForProxy.put(method, chainedMock); return chainedMock; }
From source file:name.ikysil.beanpathdsl.codegen.Context.java
private boolean isExcluded(Class<?> clazz) { if (clazz.isPrimitive() || clazz.isAnonymousClass() || clazz.isLocalClass() || clazz.isInterface() || clazz.isSynthetic() || clazz.isEnum() || !Modifier.isPublic(clazz.getModifiers()) || (clazz.getPackage() == null)) { return true; }/* www. j a v a2 s . c o m*/ IncludedClass includedConfig = includedClasses.get(clazz); if (includedConfig != null) { return false; } ExcludedClass excludedConfig = excludedClasses.get(clazz); if (excludedConfig != null) { return true; } for (ExcludedPackage excludedPackage : excludedPackages) { if (excludedPackage.match(clazz.getPackage())) { return true; } } return false; }
From source file:org.apache.openjpa.enhance.PCSubclassValidator.java
public void assertCanSubclass() { Class superclass = meta.getDescribedType(); String name = superclass.getName(); if (superclass.isInterface()) addError(loc.get("subclasser-no-ifaces", name), meta); if (Modifier.isFinal(superclass.getModifiers())) addError(loc.get("subclasser-no-final-classes", name), meta); if (Modifier.isPrivate(superclass.getModifiers())) addError(loc.get("subclasser-no-private-classes", name), meta); if (PersistenceCapable.class.isAssignableFrom(superclass)) addError(loc.get("subclasser-super-already-pc", name), meta); try {/*from w w w.j a va2 s . c o m*/ Constructor c = superclass.getDeclaredConstructor(new Class[0]); if (!(Modifier.isProtected(c.getModifiers()) || Modifier.isPublic(c.getModifiers()))) addError(loc.get("subclasser-private-ctor", name), meta); } catch (NoSuchMethodException e) { addError(loc.get("subclasser-no-void-ctor", name), meta); } // if the BCClass we loaded is already pc and the superclass is not, // then we should never get here, so let's make sure that the // calling context is caching correctly by throwing an exception. if (pc.isInstanceOf(PersistenceCapable.class) && !PersistenceCapable.class.isAssignableFrom(superclass)) throw new InternalException(loc.get("subclasser-class-already-pc", name)); if (AccessCode.isProperty(meta.getAccessType())) checkPropertiesAreInterceptable(); if (errors != null && !errors.isEmpty()) throw new UserException(errors.toString()); else if (contractViolations != null && !contractViolations.isEmpty() && log.isWarnEnabled()) log.warn(contractViolations.toString()); }
From source file:com.basistech.rosette.apimodel.ModelTest.java
@Test public void packageTest() throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException { Reflections reflections = new Reflections(this.getClass().getPackage().getName(), new SubTypesScanner(false)); Set<Class<?>> allClasses = reflections.getSubTypesOf(Object.class); for (Object clazz : allClasses) { String className = ((Class) clazz).getName(); if (className.contains("com.basistech.rosette.dm")) { continue; }/*from w w w. ja v a 2 s . c o m*/ if (className.contains("Adm")) { continue; // these are too hard. } if (className.endsWith(".ModelTest")) { continue; } if (className.endsWith(".NonNullTest")) { continue; } if (className.endsWith("Mixin")) { continue; } if (className.endsWith("Builder")) { continue; } if (className.contains(".batch.")) { // there are polymorphism issues in here for this test strategy. continue; } Class c = Class.forName(className); if (Modifier.isAbstract(c.getModifiers())) { continue; } Constructor[] ctors = c.getDeclaredConstructors(); if (ctors.length == 0) { continue; } Constructor ctor = ctors[0]; if (ctor.getParameterTypes().length == 0) { continue; // don't want empty constructor } Object o1; if (Modifier.isPublic(ctor.getModifiers())) { boolean oldInputStreams = inputStreams; try { if (className.endsWith("ConstantsResponse")) { inputStreams = false; // special case due to Object in there. } o1 = createObject(ctor); } finally { inputStreams = oldInputStreams; } // serialize // for a request, we might need a view ObjectWriter writer = mapper.writerWithView(Object.class); if (o1 instanceof DocumentRequest) { DocumentRequest r = (DocumentRequest) o1; if (r.getRawContent() instanceof String) { writer = mapper.writerWithView(DocumentRequestMixin.Views.Content.class); } } String json = writer.writeValueAsString(o1); // deserialize Object o2 = mapper.readValue(json, (Class<? extends Object>) clazz); // verify assertEquals(o1, o2); } } }
From source file:org.guicerecipes.spring.support.AutowiredMemberProvider.java
/** * Returns a new instance of the given class if its a public non abstract class which has a public zero argument constructor otherwise returns null *//*w w w . j a v a 2s .co m*/ protected Object tryCreateInstance(Class<?> type) { Object answer = null; int modifiers = type.getModifiers(); if (!Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !type.isInterface()) { // if its a concrete class with no args make one Constructor<?> constructor = null; try { constructor = type.getConstructor(); } catch (NoSuchMethodException e) { // ignore } if (constructor != null) { if (Modifier.isPublic(constructor.getModifiers())) { try { answer = constructor.newInstance(); } catch (InstantiationException e) { throw new ProvisionException("Failed to instantiate " + constructor, e); } catch (IllegalAccessException e) { throw new ProvisionException("Failed to instantiate " + constructor, e); } catch (InvocationTargetException ie) { Throwable e = ie.getTargetException(); throw new ProvisionException("Failed to instantiate " + constructor, e); } } } } return answer; }
From source file:org.opt4j.config.ModuleAutoFinder.java
/** * Returns all not abstract classes that implement {@link PropertyModule}. * //from ww w.java 2 s . c o m * @return all property modules */ protected Collection<Class<? extends Module>> getAll() { Starter starter = new Starter(); Collection<File> files = starter.addPlugins(); classLoader = ClassLoader.getSystemClassLoader(); String paths = System.getProperty("java.class.path"); StringTokenizer st = new StringTokenizer(paths, ";\n:"); while (st.hasMoreTokens()) { String path = st.nextToken(); File f = new File(path); if (f.exists()) { try { f = f.getCanonicalFile(); files.add(f); } catch (IOException e) { e.printStackTrace(); } } } List<Class<?>> classes = new ArrayList<Class<?>>(); for (File file : files) { if (isJar(file)) { try { classes.addAll(getAllClasses(new ZipFile(file))); } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (UnsupportedClassVersionError e) { System.err.println(file + " not supported: bad version number"); } } else { classes.addAll(getAllClasses(file)); } } List<Class<? extends Module>> modules = new ArrayList<Class<? extends Module>>(); for (Class<?> clazz : classes) { if (Opt4JModule.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) { Class<? extends Module> module = clazz.asSubclass(Module.class); Ignore i = module.getAnnotation(Ignore.class); if (i == null && !module.isAnonymousClass() && accept.transform(module) && !ignore.transform(module)) { modules.add(module); invokeOut("Add module: " + module.toString()); } } } return modules; }