/** * 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 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())); }
private void generateConstructors(JavaClass jClass, String superClassName) { for (Constructor baseCtor : _cl.getDeclaredConstructors()) { if (Modifier.isPrivate(baseCtor.getModifiers())) continue; generateConstructor(jClass, superClassName, baseCtor); } }
public static JoinPoint.StaticPart makeEncSJP(Member member) { Signature sig = null; String kind = null; if (member instanceof Method) { Method method = (Method) member; sig = new MethodSignatureImpl( method.getModifiers(), method.getName(), method.getDeclaringClass(), method.getParameterTypes(), new String[method.getParameterTypes().length], method.getExceptionTypes(), method.getReturnType()); kind = JoinPoint.METHOD_EXECUTION; } else if (member instanceof Constructor) { Constructor cons = (Constructor) member; sig = new ConstructorSignatureImpl( cons.getModifiers(), cons.getDeclaringClass(), cons.getParameterTypes(), new String[cons.getParameterTypes().length], cons.getExceptionTypes()); kind = JoinPoint.CONSTRUCTOR_EXECUTION; } else { throw new IllegalArgumentException("member must be either a method or constructor"); } return new JoinPointImpl.EnclosingStaticPartImpl(-1, kind, sig, null); }
/** Checks whether the constructor parsed from API xml file and Java reflection are compliant. */ @SuppressWarnings("unchecked") private void checkConstructorCompliance() { for (JDiffConstructor con : jDiffConstructors) { try { Constructor<?> c = findMatchingConstructor(con); if (c == null) { mResultObserver.notifyFailure( SignatureTestActivity.FAILURE_TYPE.MISSING_METHOD, con.toReadableString(mAbsoluteClassName), "No method with correct signature found:" + con.toSignatureString()); } else { if (c.isVarArgs()) { // some method's parameter are variable args con.mModifier |= METHOD_MODIFIER_VAR_ARGS; } if (c.getModifiers() != con.mModifier) { mResultObserver.notifyFailure( SignatureTestActivity.FAILURE_TYPE.MISMATCH_METHOD, con.toReadableString(mAbsoluteClassName), "Non-compatible method found when looking for " + con.toSignatureString()); } } } catch (Exception e) { SignatureTestLog.e("Got exception when checking constructor compliance", e); mResultObserver.notifyFailure( SignatureTestActivity.FAILURE_TYPE.CAUGHT_EXCEPTION, con.toReadableString(mAbsoluteClassName), "Exception!"); } } }
@SuppressWarnings("unchecked") private boolean hasValidConstructor(java.lang.Class<?> aClass) { // The cast below is not necessary with the Java 5 compiler, but necessary with the Java 6 // compiler, // where the return type of Class.getDeclaredConstructors() was changed // from Constructor<T>[] to Constructor<?>[] Constructor<? extends TestCase>[] constructors = (Constructor<? extends TestCase>[]) aClass.getConstructors(); for (Constructor<? extends TestCase> constructor : constructors) { if (Modifier.isPublic(constructor.getModifiers())) { java.lang.Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length == 0 || (parameterTypes.length == 1 && parameterTypes[0] == String.class)) { return true; } } } Log.i( LOG_TAG, String.format( "TestCase class %s is missing a public constructor with no parameters " + "or a single String parameter - skipping", aClass.getName())); return false; }
/** * Make the given constructor accessible, explicitly setting it accessible if necessary. The * <code>setAccessible(true)</code> method is only called when actually necessary, to avoid * unnecessary conflicts with a JVM SecurityManager (if active). * * @param ctor the constructor to make accessible * @see java.lang.reflect.Constructor#setAccessible */ public static void makeAccessible(Constructor<?> ctor) { if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) { ctor.setAccessible(true); } }
public static <T> Constructor<T> findConstructor(Class<T> cls, boolean canFixAccess) throws IllegalArgumentException { try { Constructor<T> ctor = cls.getDeclaredConstructor(); if (canFixAccess) { checkAndFixAccess(ctor); } else { // Has to be public... if (!Modifier.isPublic(ctor.getModifiers())) { throw new IllegalArgumentException( "Default constructor for " + cls.getName() + " is not accessible (non-public?): not allowed to try modify access via Reflection: can not instantiate type"); } } return ctor; } catch (NoSuchMethodException e) {; } catch (Exception e) { ClassUtil.unwrapAndThrowAsIAE( e, "Failed to find default constructor of class " + cls.getName() + ", problem: " + e.getMessage()); } return null; }
/** * Test to see if a private Constructor exists. * * @throws Exception to JUnit, indicates error */ @Test public void testPrivateCtor() throws Exception { Constructor<?> privateCtor = Helper.class.getDeclaredConstructors()[0]; assertTrue(Modifier.isPrivate(privateCtor.getModifiers())); privateCtor.setAccessible(true); privateCtor.newInstance(new Object[] {}); }
/** * Finds constructors of the specified access level in the supplied class. * * @param c the class to search in * @param level the access level to look for * @param sb the StringBuffer where the results should be added */ private static void listConstructors(Class c, int level, StringBuffer sb) { Constructor[] constrs = c.getDeclaredConstructors(); Constructor constructor; Class[] exceptions; StringBuffer cons; for (int index = 0; index < constrs.length; index++) { constructor = constrs[index]; if (isAccessible(constructor.getModifiers(), level)) { cons = new StringBuffer(100); cons.append(printConstructor(constructor.getName(), constructor.getParameterTypes())); // Add exceptions exceptions = constructor.getExceptionTypes(); if (exceptions.length > 0) { cons.append(printExceptions(exceptions)); } else { cons.append(NIL); } cons.append(END_PAREN); if (sb.toString().lastIndexOf(cons.toString()) == -1) { sb.append(cons); } } } }
/** * Tests the private constructor. * * @throws Exception if oops */ @Test public void testConstructorIsPrivate() throws Exception { Constructor<Sanity> constructor = Sanity.class.getDeclaredConstructor(); Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(); }
@Test public void checkThatConstructorIsProtected() { for (Constructor<?> constr : Earth.class.getDeclaredConstructors()) { assertTrue( "Constructors should be protected to allow subclasses of singleton", Modifier.isProtected(constr.getModifiers())); } }
@Test public void testConstructorIsPrivate() throws Exception { Constructor<ReflectionUtils> con = ReflectionUtils.class.getDeclaredConstructor(); Assert.assertEquals(Modifier.PRIVATE, con.getModifiers() & Modifier.PRIVATE); con.setAccessible(true); Assert.assertNotNull(con.newInstance()); }
public boolean isConstructorAccessibleForDecoding(Class clazz) { try { Constructor constr = clazz.getDeclaredConstructor(null); return isWithin(constr.getModifiers(), decodingAccessScope.get(CONSTRUCTOR_SCOPE)); } catch (Exception e) { return false; } }
/** java.lang.reflect.InvocationTargetException#InvocationTargetException() */ public void test_Constructor() throws Exception { Constructor<InvocationTargetException> ctor = InvocationTargetException.class.getDeclaredConstructor(); assertNotNull("Parameterless constructor does not exist.", ctor); assertTrue("Constructor is not protected", Modifier.isProtected(ctor.getModifiers())); // create an instance of a subtype using this constructor SubInvocationTargetException subException = new SubInvocationTargetException(); }
private Class<?> loadBeanClass() { if (beanClass == null) { String className = beanInfo.getClassName(); Class<?> clazz = loadClass(className); ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance(); if (!associate.isDevModeEnabled()) { beanClass = clazz; } // validate the bean class is public and has a public // no-arg ctor int classModifiers = clazz.getModifiers(); if (!Modifier.isPublic(classModifiers)) { String message = MessageUtils.getExceptionMessageString( MessageUtils.MANAGED_BEAN_CLASS_IS_NOT_PUBLIC_ERROR_ID, className, beanInfo.getName()); queueMessage(message); } if (Modifier.isInterface(classModifiers) || Modifier.isAbstract(classModifiers)) { String message = MessageUtils.getExceptionMessageString( MessageUtils.MANAGED_BEAN_CLASS_IS_ABSTRACT_ERROR_ID, className, beanInfo.getName()); queueMessage(message); } try { Constructor ctor = clazz.getConstructor(RIConstants.EMPTY_CLASS_ARGS); if (!Modifier.isPublic(ctor.getModifiers())) { String message = MessageUtils.getExceptionMessageString( MessageUtils.MANAGED_BEAN_CLASS_NO_PUBLIC_NOARG_CTOR_ERROR_ID, className, beanInfo.getName()); queueMessage(message); } } catch (NoSuchMethodException nsme) { String message = MessageUtils.getExceptionMessageString( MessageUtils.MANAGED_BEAN_CLASS_NO_PUBLIC_NOARG_CTOR_ERROR_ID, className, beanInfo.getName()); queueMessage(message); } if (!hasMessages()) { // class is ok, scan for annotations this.isInjectible = scanForAnnotations(clazz); } return clazz; } return beanClass; }
@Test public void constructorShouldBePrivate() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor<MultiDex> constructor = MultiDex.class.getDeclaredConstructor(); assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(); }
@Test public void testConstructor() throws Exception { Class<HMAC> c = HMAC.class; assertEquals(1, c.getDeclaredConstructors().length); Constructor<HMAC> constructor = c.getDeclaredConstructor(); assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(); }
public void setConstructor(Constructor<?> constructor, List<String> fields) { check(implInterface || !dataTypeIn.isInterface()); checkNotNull(constructor); checkNotNull(fields); check(this.constructor == null, "Constructor is already set: %s", this.constructor); check(!isPrivate(constructor.getModifiers()), "Constructor cannot be private: %s", constructor); check(constructor.getGenericParameterTypes().length == fields.size()); this.constructor = constructor; this.constructorParams = fields; }
/** * This method tests the private constructor of {@code Descriptions} for the tests coverage.. * * @throws NoSuchMethodException * @throws SecurityException * @throws java.lang.reflect.InvocationTargetException * @throws IllegalAccessException * @throws InstantiationException * @throws IllegalArgumentException */ @Test public void test_private_constructor_for_the_tests_coverage() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Constructor<Descriptions> constructor = Descriptions.class.getDeclaredConstructor(); assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); constructor.setAccessible(true); constructor.newInstance(); constructor.setAccessible(false); }
/** * Returns a new injection point for the injectable constructor of {@code type}. * * @param type a concrete type with exactly one constructor annotated {@literal @}{@link Inject}, * or a no-arguments constructor that is not private. * @throws ConfigurationException if there is no injectable constructor, more than one injectable * constructor, or if parameters of the injectable constructor are malformed, such as a * parameter with multiple binding annotations. */ public static InjectionPoint forConstructorOf(TypeLiteral<?> type) { Class<?> rawType = getRawType(type.getType()); Errors errors = new Errors(rawType); Constructor<?> injectableConstructor = null; for (Constructor<?> constructor : rawType.getDeclaredConstructors()) { boolean optional; Inject guiceInject = constructor.getAnnotation(Inject.class); if (guiceInject == null) { javax.inject.Inject javaxInject = constructor.getAnnotation(javax.inject.Inject.class); if (javaxInject == null) { continue; } optional = false; } else { optional = guiceInject.optional(); } if (optional) { errors.optionalConstructor(constructor); } if (injectableConstructor != null) { errors.tooManyConstructors(rawType); } injectableConstructor = constructor; checkForMisplacedBindingAnnotations(injectableConstructor, errors); } errors.throwConfigurationExceptionIfErrorsExist(); if (injectableConstructor != null) { return new InjectionPoint(type, injectableConstructor); } // If no annotated constructor is found, look for a no-arg constructor instead. try { Constructor<?> noArgConstructor = rawType.getDeclaredConstructor(); // Disallow private constructors on non-private classes (unless they have @Inject) if (Modifier.isPrivate(noArgConstructor.getModifiers()) && !Modifier.isPrivate(rawType.getModifiers())) { errors.missingConstructor(rawType); throw new ConfigurationException(errors.getMessages()); } checkForMisplacedBindingAnnotations(noArgConstructor, errors); return new InjectionPoint(type, noArgConstructor); } catch (NoSuchMethodException e) { errors.missingConstructor(rawType); throw new ConfigurationException(errors.getMessages()); } }
@Override protected boolean matchesSafely(final Class<?> clazz) { try { Constructor<?> constructor = clazz.getDeclaredConstructor(); constructor.setAccessible(true); constructor.newInstance(); return Modifier.isPrivate(constructor.getModifiers()); } catch (final Exception ignored) { } return false; }
/** * Create a name for the given reflected constructor. The resulting name will be in a resolved * state. */ public MemberName(Constructor ctor) { Object[] typeInfo = {void.class, ctor.getParameterTypes()}; init( ctor.getDeclaringClass(), CONSTRUCTOR_NAME, typeInfo, flagsMods(IS_CONSTRUCTOR, ctor.getModifiers())); // fill in vmtarget, vmindex while we have ctor in hand: MethodHandleNatives.init(this, ctor); assert (isResolved()); }
/** * Visit every class/interface this proxy should implement, and generate the appropriate bytecode * for delegation if available. * * @param clazz an class for which to generate bytecode */ private void visitClass(final Class clazz) { Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { Class<?>[] exceptionTypes = method.getExceptionTypes(); String[] exceptions = new String[exceptionTypes.length]; for (int i = 0; i < exceptions.length; i++) { exceptions[i] = BytecodeHelper.getClassInternalName(exceptionTypes[i]); } // for each method defined in the class, generate the appropriate delegation bytecode visitMethod( method.getModifiers(), method.getName(), BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes()), null, exceptions); } Constructor[] constructors = clazz.getDeclaredConstructors(); for (Constructor method : constructors) { Class<?>[] exceptionTypes = method.getExceptionTypes(); String[] exceptions = new String[exceptionTypes.length]; for (int i = 0; i < exceptions.length; i++) { exceptions[i] = BytecodeHelper.getClassInternalName(exceptionTypes[i]); } // for each method defined in the class, generate the appropriate delegation bytecode visitMethod( method.getModifiers(), "<init>", BytecodeHelper.getMethodDescriptor(Void.TYPE, method.getParameterTypes()), null, exceptions); } for (Class intf : clazz.getInterfaces()) { visitClass(intf); } Class superclass = clazz.getSuperclass(); if (superclass != null) visitClass(superclass); // Ultimately, methods can be available in the closure map which are not defined by the // superclass // nor the interfaces for (Map.Entry<String, Boolean> entry : delegatedClosures.entrySet()) { Boolean visited = entry.getValue(); if (!visited) { String name = entry.getKey(); if (!"*".equals(name)) { // generate a new method visitMethod(ACC_PUBLIC, name, "([Ljava/lang/Object;)Ljava/lang/Object;", null, null); } } } }
private Object preprocess(Constructor<?> method) { try { return preprocessMethodOrConstructor( method.getModifiers(), null, method.getDeclaringClass(), null, method.getParameterTypes(), method.getExceptionTypes()); } catch (Exception e) { return "<" + e + ">"; } }
public static void validateNoargsConstructor(Class<?> clazz) { if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers())) { Constructor<?>[] constructors = clazz.getConstructors(); for (Constructor<?> constructor : constructors) { if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 0) { return; } } throw new AchillesException( "The class '" + clazz.getCanonicalName() + "' should have a public default constructor"); } }
private static <T> void checkIsValidPartial(Class<T> cls) { checkArgument(isAbstract(cls.getModifiers()), "Partial class must be abstract"); checkArgument( cls.getDeclaredConstructors().length == 1, "Partial class %s must have exactly one constructor (found %s)", cls, cls.getDeclaredConstructors().length); Constructor<?> constructor = cls.getDeclaredConstructors()[0]; checkArgument( !isPrivate(constructor.getModifiers()), "Partial class %s must have a package-visible constructor", cls); }
public static boolean hasValidDefaultConstructor(Class cls) { try { if (cls != null) { Constructor c = cls.getConstructor(new Class[] {}); int mod = c.getModifiers(); return Modifier.isPublic(mod); } } catch (Throwable t) { return false; } return false; }
@Test public void shouldBeWellDefined() throws Exception { assertThat(mKlass.getSuperclass()).isEqualTo(Object.class); assertThat(Modifier.isFinal(mKlass.getModifiers())).isTrue(); assertThat(mKlass.getDeclaredConstructors()).hasSize(1); final Constructor<?> constructor = mKlass.getDeclaredConstructor(); assertThat(constructor.isAccessible()).isFalse(); assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); for (final Method method : mKlass.getDeclaredMethods()) { assertThat(Modifier.isStatic(method.getModifiers())).describedAs(method.getName()).isTrue(); } }
/** Creates an instance. */ private DefaultUIComponentFactory(Class<?> type) { if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) { throw new IllegalArgumentException("Type is not instantiable: " + type.getName()); } Constructor cons; try { cons = type.getDeclaredConstructor(MetaUIComponent.class); } catch (ReflectiveOperationException ex) { throw new IllegalArgumentException(ex); } if (Modifier.isPublic(cons.getModifiers()) == false) { throw new IllegalArgumentException("Constructor is not public: " + cons); } this.constructor = cons; }