@SuppressWarnings("rawtypes") private <O extends Operator> O newInstance(Class<O> c) { if (c.isInterface()) { return null; } if (Modifier.isAbstract(c.getModifiers())) { return null; } final Class<?>[] paramTypes; final Object[] args; if (Modifier.isStatic(c.getModifiers())) { paramTypes = ArrayUtils.EMPTY_CLASS_ARRAY; args = ArrayUtils.EMPTY_OBJECT_ARRAY; } else { paramTypes = new Class[] {getClass()}; args = new Object[] {this}; } final Constructor<O> cs = ConstructorUtils.getMatchingAccessibleConstructor(c, paramTypes); if (cs == null) { return null; } try { return cs.newInstance(args); } catch (Exception e) { throw new RuntimeException(e); } }
boolean applyArgoController(Class<?> clazz, Pattern controllerPattern) { return ArgoController.class.isAssignableFrom(clazz) && controllerPattern.matcher(clazz.getName()).matches() && !Modifier.isInterface(clazz.getModifiers()) && !Modifier.isAbstract(clazz.getModifiers()) && Modifier.isPublic(clazz.getModifiers()); }
/** * Retrieve the names of all the public static classes in the clazz * * @param clazz the object to inspect * @return list of all the names of public statics */ public String[] getPublicStaticClassNames(Class<?> clazz) { Class<?>[] classes = clazz.getClasses(); Set<String> classNames = new HashSet<String>(); for (Class<?> clazz2 : classes) { if (Modifier.isPublic(clazz2.getModifiers()) && Modifier.isStatic(clazz2.getModifiers())) { classNames.add(clazz2.getSimpleName()); } } return (String[]) classNames.toArray(new String[classNames.size()]); }
public static TypeImpl getIterableImpl(Class<?> iterClass) { if (iterClass == List.class || iterClass == Collection.class || iterClass == Iterable.class) { return new TypeImpl(iterClass, ArrayList.class); } else if (Modifier.isAbstract(iterClass.getModifiers()) || Modifier.isInterface(iterClass.getModifiers())) { throw new RuntimeException( "Cannot find appropriate implementation of collection type: " + iterClass.getName()); } return new TypeImpl(iterClass, iterClass); }
/** * Does basic sanity checks to make sure the constructor can be properly invoked by our generated * class. * * @param clazz */ private void validateClass(Class<? extends DataSerializable> clazz) { Assert.isTrue( !Modifier.isAbstract(clazz.getModifiers()), "Cannot instantiate abstract classes"); Assert.isTrue(Modifier.isPublic(clazz.getModifiers()), "Only public classes are supported"); try { Constructor<? extends DataSerializable> ctor = clazz.getConstructor(); Assert.isTrue(Modifier.isPublic(ctor.getModifiers()), "Default constructor is not public"); } catch (Exception ex) { throw new IllegalArgumentException("Class " + clazz + " unsuitable for instantiation", ex); } }
public void test_immutable() throws Exception { Class<CopticChronology> cls = CopticChronology.class; assertTrue(Modifier.isPublic(cls.getModifiers())); assertTrue(Modifier.isFinal(cls.getModifiers())); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { if (Modifier.isStatic(field.getModifiers()) == false) { assertTrue(Modifier.isPrivate(field.getModifiers())); assertTrue(Modifier.isFinal(field.getModifiers())); } } }
public void testImmutable() { Class<Fastq> cls = Fastq.class; assertTrue(Modifier.isPublic(cls.getModifiers())); assertTrue(Modifier.isFinal(cls.getModifiers())); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { assertTrue(Modifier.isPrivate(field.getModifiers())); assertTrue( Modifier.isFinal(field.getModifiers()) || (Modifier.isVolatile(field.getModifiers()) && Modifier.isTransient(field.getModifiers()))); } }
@Test public void test_immutable() { Class<MinguoDate> cls = MinguoDate.class; assertTrue(Modifier.isPublic(cls.getModifiers())); assertTrue(Modifier.isFinal(cls.getModifiers())); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { if (Modifier.isStatic(field.getModifiers()) == false) { assertTrue(Modifier.isPrivate(field.getModifiers())); assertTrue(Modifier.isFinal(field.getModifiers())); } } }
public static TypeImpl getMapImpl(Class<?> mapClass) { if (mapClass == Map.class || mapClass == AbstractMap.class) { return new TypeImpl(mapClass, HashMap.class); } else if (mapClass == ConcurrentMap.class) { return new TypeImpl(mapClass, ConcurrentHashMap.class); } else if (SortedMap.class.isAssignableFrom(mapClass)) { return new TypeImpl(mapClass, TreeMap.class); } else if (Modifier.isAbstract(mapClass.getModifiers()) || Modifier.isInterface(mapClass.getModifiers())) { throw new RuntimeException( "Cannot find appropriate implementation of collection type: " + mapClass.getName()); } return new TypeImpl(mapClass, mapClass); }
private JavaTypeDescriptor arrayOfType(Class type) { if (type.isArray()) { return new ArrayDescriptorImpl( buildName("[" + type.getName()), type.getModifiers(), arrayOfType(type.getComponentType())); } if (type.isPrimitive()) { return Primitives.primitiveArrayDescriptor(type); } else { return new ArrayDescriptorImpl( buildName("[" + type.getName()), type.getModifiers(), getType(buildName(type.getName()))); } }
// ----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = NullConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); }
public void build() throws Exception { names = Generic.set(); int access = superclass.getModifiers(); if ((access & Modifier.FINAL) != 0) { throw new InstantiationException("can't subclass final class"); } access = Modifier.PUBLIC | Modifier.SYNCHRONIZED; classfile = new ClassFile(myClass, mapClass(superclass), access); addProxy(); addConstructors(superclass); classfile.addInterface("org/python/core/PyProxy"); Set<String> seenmethods = Generic.set(); addMethods(superclass, seenmethods); for (Class<?> iface : interfaces) { if (iface.isAssignableFrom(superclass)) { Py.writeWarning("compiler", "discarding redundant interface: " + iface.getName()); continue; } classfile.addInterface(mapClass(iface)); addMethods(iface, seenmethods); } doConstants(); addClassDictInit(); }
private Object newInstance(Class type) { try { return type.newInstance(); } catch (Exception ex) { try { // Try a private constructor. Constructor constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (SecurityException ignored) { } catch (NoSuchMethodException ignored) { if (type.isArray()) throw new SerializationException( "Encountered JSON object when expected array of type: " + type.getName(), ex); else if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers())) throw new SerializationException( "Class cannot be created (non-static member class): " + type.getName(), ex); else throw new SerializationException( "Class cannot be created (missing no-arg constructor): " + type.getName(), ex); } catch (Exception privateConstructorException) { ex = privateConstructorException; } throw new SerializationException( "Error constructing instance of class: " + type.getName(), ex); } }
@Test public void should_generate_assertion_for_classes_in_package_using_provided_class_loader() throws Exception { ClassLoader customClassLoader = new MyClassLoader(Thread.currentThread().getContextClassLoader()); Set<Class<?>> classes = collectClasses(customClassLoader, "org.assertj.assertions.generator.data"); for (Class<?> clazz : classes) { assertThat(clazz.isAnonymousClass()) .as("check that " + clazz.getSimpleName() + " is not anonymous") .isFalse(); assertThat(clazz.isLocalClass()) .as("check that " + clazz.getSimpleName() + " is not local") .isFalse(); assertThat(isPublic(clazz.getModifiers())) .as("check that " + clazz.getSimpleName() + " is public") .isTrue(); logger.info("Generating assertions for {}", clazz.getName()); final ClassDescription classDescription = converter.convertToClassDescription(clazz); File customAssertionFile = assertionGenerator.generateCustomAssertionFor(classDescription); logger.info( "Generated {} assertions file -> {}", clazz.getSimpleName(), customAssertionFile.getAbsolutePath()); } }
protected <T> T getProxy(final Class<T> proxyClass) { if (proxyClass == null || Modifier.isFinal(proxyClass.getModifiers())) { return null; } return proxyClass.isInterface() ? proxyForInterface(proxyClass) : proxyForClass(proxyClass); }
public static boolean isValidResourceClass(Class<?> c) { if (c.isInterface() || Modifier.isAbstract(c.getModifiers())) { LOG.info("Ignoring invalid resource class " + c.getName()); return false; } return true; }
public static void register(Class<? extends Event> pore) { checkNotNull(pore, "pore"); Class<? extends org.spongepowered.api.event.Event> sponge = null; for (Constructor<?> constructor : pore.getConstructors()) { Class<?>[] parameters = constructor.getParameterTypes(); if (parameters.length == 1) { Class<?> parameter = parameters[0]; if (org.spongepowered.api.event.Event.class.isAssignableFrom(parameter)) { sponge = parameter.asSubclass(org.spongepowered.api.event.Event.class); } } } checkArgument(sponge != null, "No event constructor found in %s", pore); Class<?> superClass = pore.getSuperclass(); checkState( !Modifier.isAbstract(superClass.getModifiers()) && superClass.getName().startsWith("org.bukkit.event"), "Not a Bukkit handle event %s", superClass); Class<? extends Event> handle = superClass.asSubclass(Event.class); HandlerList list = SimplePluginManager.getEventListeners(handle); list.addAdapter(create(pore, sponge)); }
/** Sets the access flag of a member */ @Override protected void setAccessFlag(final Member m) { final int mods = m.getModifiers(); final Class c = m.getDeclaringClass(); final int cmods = c.getModifiers(); final String pkg = this.importationManager.getCurrentPackage(); final String mp = getPackageName(c); final boolean samePkg = pkg.equals(mp); if (Modifier.isPublic(cmods) || samePkg) { if (Modifier.isPublic(mods)) { ((AccessibleObject) m).setAccessible(true); } else if (Modifier.isProtected(mods)) { if (c.isAssignableFrom(this.declaringClass.getSuperclass()) || samePkg) { ((AccessibleObject) m).setAccessible(true); } } else if (!Modifier.isPrivate(mods)) { if (samePkg) { ((AccessibleObject) m).setAccessible(true); } } else { if (this.declaringClass == c || isInnerClass(this.declaringClass, c)) { ((AccessibleObject) m).setAccessible(true); } } } }
/** * Checks if the class under test has compliant modifiers compared to the API. * * @return true if modifiers are compliant. */ private boolean checkClassModifiersCompliance() { int reflectionModifier = mClass.getModifiers(); int apiModifier = mModifier; // If the api class isn't abstract if (((apiModifier & Modifier.ABSTRACT) == 0) && // but the reflected class is ((reflectionModifier & Modifier.ABSTRACT) != 0) && // and it isn't an enum !isEnumType()) { // that is a problem return false; } // ABSTRACT check passed, so mask off ABSTRACT reflectionModifier &= ~Modifier.ABSTRACT; apiModifier &= ~Modifier.ABSTRACT; if (isAnnotation()) { reflectionModifier &= ~CLASS_MODIFIER_ANNOTATION; } if (mClass.isInterface()) { reflectionModifier &= ~(Modifier.INTERFACE); } if (isEnumType() && mClass.isEnum()) { reflectionModifier &= ~CLASS_MODIFIER_ENUM; } return ((reflectionModifier == apiModifier) && (isEnumType() == mClass.isEnum())); }
/** * This default implementation checks that the given class is not abstract and that it has either * a {@link RunWith} class-level annotation or at least one of its methods is annotated with * {@link Test}. * * @param bundle The class's hosting bundle * @param c * @return Returns <code>true</code> if the class hosts a JUnit test methods. <code>false</code> * otherwise. */ protected boolean acceptClass(Bundle bundle, Class<?> c) { if ((c.getModifiers() & Modifier.ABSTRACT) != 0) { return false; } if (junit.framework.Test.class.isAssignableFrom(c)) { // JUnit 3 support return true; } if (c.getAnnotation(RunWith.class) != null) { // class-level check is ok return true; } else { // look for annotated Test methods Method[] methods = c.getMethods(); if (methods != null) { for (Method m : methods) { if (m.getAnnotation(Test.class) != null) { return true; } } } } return false; }
public JavaType findType(String name) { if (_bindings == null) { _resolve(); } JavaType t = _bindings.get(name); if (t != null) { return t; } if (_placeholders != null && _placeholders.contains(name)) { return UNBOUND; } // New with 1.7: check parent context if (_parentBindings != null) { return _parentBindings.findType(name); } // nothing found, so... // Should we throw an exception or just return null? /* [JACKSON-499] 18-Feb-2011, tatu: There are some tricky type bindings within * java.util, such as HashMap$KeySet; so let's punt the problem * (honestly not sure what to do -- they are unbound for good, I think) */ if (_contextClass != null) { Class<?> enclosing = _contextClass.getEnclosingClass(); if (enclosing != null) { // [JACKSON-572]: Actually, let's skip this for all non-static inner classes // (which will also cover 'java.util' type cases... if (!Modifier.isStatic(_contextClass.getModifiers())) { return UNBOUND; } // ... so this piece of code should not be needed any more /* Package pkg = enclosing.getPackage(); if (pkg != null) { // as per [JACKSON-533], also include "java.util.concurrent": if (pkg.getName().startsWith("java.util")) { return UNBOUND; } } */ } } String className; if (_contextClass != null) { className = _contextClass.getName(); } else if (_contextType != null) { className = _contextType.toString(); } else { className = "UNKNOWN"; } throw new IllegalArgumentException( "Type variable '" + name + "' can not be resolved (with context of class " + className + ")"); // t = UNBOUND; }
private void LoadClasses() { classes = new ArrayList<FileClass>(); // Load directory File dir = new File(directory); File[] files = dir.listFiles(filter); // For each file of type .class, for (File f : files) { // Load file try { URL url = f.toURI().toURL(); URL[] urls = new URL[] {url}; ClassLoader cl = new URLClassLoader(urls); Class<?> cls = cl.loadClass("builtin." + f.getName().replace(".class", "")); ArrayList<Class<?>> interfaces = getAllInterfaces(cls); for (Class<?> c : interfaces) { if (c.equals(mytype) && !Modifier.isAbstract(cls.getModifiers())) { classes.add(new FileClass(f, cls)); break; } } } catch (Exception ex) { System.err.println("Error loading class file: " + f.getAbsolutePath()); } } }
/** * Adds the new {@link StaticWidget} to the registry. * * @param clazz the class of the {@link StaticWidget}. If it is an abstract class, then it will be * ignored. */ public static void registerStaticWidget(Class<? extends StaticWidget> clazz) { if (!Modifier.isAbstract(clazz.getModifiers())) { staticWidgets.add(clazz); } // TODO made this complain if given a normal widget, or make it call // registerWidget }
/** @return the test suite */ public static Test suite() { TestSuite suite = new TestSuite(); int count = 0; for (Enumeration e = (new LoadingTestCollector()).collectTests(); e.hasMoreElements(); ) { Object o = e.nextElement(); if (!(o instanceof String)) continue; String s = (String) o; if (s.equals("org.argouml.util.DoAllTests")) continue; Class candidate; try { candidate = Class.forName(s); } catch (ClassNotFoundException exception) { System.err.println("Cannot load class: " + s); continue; } if (!Modifier.isAbstract(candidate.getModifiers())) { suite.addTest(new TestSuite(candidate)); count++; } } System.out.println("Number of test classes found: " + count); return suite; }
/** * Register a custom argument creator factory for an unknown final class * * @param clazz The class for which this factory should be used * @param creator The argument factory * @param <T> */ public static <T> void registerFinalClassArgumentCreator( Class<T> clazz, FinalClassArgumentCreator<T> creator) { if ((clazz.getModifiers() & Modifier.FINAL) == 0) throw new RuntimeException( "A custom argument creator can be registered only for final classes"); FINAL_CLASS_ARGUMENT_CREATORS.put(clazz, creator); }
/** * Returns the desired Method much like <code>Class.getMethod</code>, however it ensures that the * returned Method is from a public class or interface and not from an anonymous inner class. This * means that the Method is invokable and doesn't fall foul of Java bug <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>). <code> * <pre>Set set = Collections.unmodifiableSet(...); * Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]); * Object result = method.invoke(set, new Object[]);</pre></code> * * @param cls the class to check, not null * @param methodName the name of the method * @param parameterTypes the list of parameters * @return the method * @throws NullPointerException if the class is null * @throws SecurityException if a a security violation occured * @throws NoSuchMethodException if the method is not found in the given class or if the metothod * doen't conform with the requirements */ public static Method getPublicMethod(Class<?> cls, String methodName, Class<?> parameterTypes[]) throws SecurityException, NoSuchMethodException { Method declaredMethod = cls.getMethod(methodName, parameterTypes); if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) { return declaredMethod; } List<Class<?>> candidateClasses = new ArrayList<Class<?>>(); candidateClasses.addAll(getAllInterfaces(cls)); candidateClasses.addAll(getAllSuperclasses(cls)); for (Class<?> candidateClass : candidateClasses) { if (!Modifier.isPublic(candidateClass.getModifiers())) { continue; } Method candidateMethod; try { candidateMethod = candidateClass.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { continue; } if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) { return candidateMethod; } } throw new NoSuchMethodException( "Can't find a public method for " + methodName + " " + ArrayUtils.toString(parameterTypes)); }
/** * @param expectedType expected Type * @return a {@link EntityFactory} instance for specified type. * @throws NullPointerException if expectedType * @throws IllegalArgumentException if no factory can be provided */ @SuppressWarnings("unchecked") public <T> EntityFactory<T> newInstance(final Class<T> expectedType) throws NullPointerException, IllegalArgumentException { // in a registered factory ? EntityFactories.EntityFactory<?> factory = factories.get(expectedType); if (factory == null) { // should we use a proxy ? if (expectedType.isInterface() || Modifier.isAbstract(expectedType.getModifiers())) { final MetaEntityContext metaEntityContext = metaEntityContextProvider.find(Reference.newReferenceOnEntityClass(expectedType)); factory = EntityFactories.newEntityProxyDynamicFactory(expectedType, metaEntityContext); } else // EntityDynamic if (EntityDynamic.class.getName().equals(expectedType.getName())) { // build factory for class factory = EntityFactories.newEntityDynamicFactory(MetaModel.getEntityDynamicContext()); } else // default Factory ? { if (!enableDefaultFactory) { throw new IllegalArgumentException( StringUtils.format("No EntityFactory for %s", expectedType)); } if (!Entity.class.isAssignableFrom(expectedType)) { throw new IllegalArgumentException( StringUtils.format( "No EntityFactory can be created for %s (Not assignable to Entity interface)", expectedType)); } factory = buildDefaultEntityFactory(expectedType); } // register for later factories.put(expectedType, factory); } return (EntityFactory<T>) factory; }
public static void main(String[] args) { String name; if (args.length > 0) { name = args[0]; } else { Scanner in = new Scanner(System.in); System.out.println("Enter class name (e.g. java.util.Date ):)"); name = in.next(); } try { Class<?> aClass = Class.forName(name); Class<?> superclass = aClass.getSuperclass(); String modifiers = Modifier.toString(aClass.getModifiers()); if (modifiers.length() > 0) { System.out.print(modifiers + " "); } System.out.print("class " + name); if (superclass != null && superclass != Object.class) { System.out.print(" extends " + superclass.getName()); } System.out.print("\n{\n"); printConstructors(aClass); System.out.println(); printMethods(aClass); System.out.println(); printFields(aClass); System.out.println("}"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.exit(0); }
private ITemplate templateInstance_() { if (!isValid) return NULL_TEMPLATE; if (null == templateInstance) { try { if (Logger.isTraceEnabled()) logger.trace("About to new template instance"); Class<?> clz = getJavaClass(); if (Logger.isTraceEnabled()) logger.trace("template java class loaded"); templateInstance = (TemplateBase) clz.newInstance(); if (Logger.isTraceEnabled()) logger.trace("template instance generated"); } catch (RythmException e) { throw e; } catch (Exception e) { throw new RuntimeException("Error load template instance for " + getKey(), e); } } if (!engine().isProdMode()) { // check parent class change Class<?> c = templateInstance.getClass(); Class<?> pc = c.getSuperclass(); if (null != pc && !Modifier.isAbstract(pc.getModifiers())) { engine().classes.getByClassName(pc.getName()); } } templateInstance.setTemplateClass(this); return templateInstance; }
public static void main(String[] args) { // read class name from command line args or user input String name; if (args.length > 0) name = args[0]; else { Scanner in = new Scanner(System.in); System.out.println("Enter class name (e.g. java.util.Date): "); name = in.next(); } try { // print class name and superclass name (if != Object) Class cl = Class.forName(name); Class supercl = cl.getSuperclass(); String modifiers = Modifier.toString(cl.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.print("class " + name); if (supercl != null && supercl != Object.class) System.out.print(" extends " + supercl.getName()); System.out.print("\n{\n"); printConstructors(cl); System.out.println(); printMethods(cl); System.out.println(); printFields(cl); System.out.println("}"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.exit(0); }