Here are the examples of the java api class java.lang.reflect.Constructor taken from open source projects.
1. StarterServiceDeployer#instantiateService()
Project: river-container
File: StarterServiceDeployer.java
File: StarterServiceDeployer.java
private Object instantiateService(ClassLoader cl, String className, String[] parms) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, InstantiationException { Class clazz = Class.forName(className, true, cl); log.log(Level.FINE, MessageNames.CLASSLOADER_IS, new Object[] { clazz.getName(), clazz.getClassLoader().toString() }); // Get this through dynamic lookup becuase it won't be in the parent // classloader! Class lifeCycleClass = Class.forName(Strings.LIFECYCLE_CLASS, true, cl); Constructor[] constructors = clazz.getDeclaredConstructors(); System.out.println("Class is " + clazz); for (int i = 0; i < constructors.length; i++) { Constructor constructor = constructors[i]; System.out.println("Found constructor " + constructor + " on " + className); } Constructor constructor = clazz.getDeclaredConstructor(new Class[] { String[].class, lifeCycleClass }); constructor.setAccessible(true); return constructor.newInstance(parms, null); }
2. Utils#getDefaultConstructor()
Project: inquiry
File: Utils.java
File: Utils.java
public static Constructor<?> getDefaultConstructor(@NonNull Class<?> cls) { final Constructor[] ctors = cls.getDeclaredConstructors(); Constructor ctor = null; for (Constructor ct : ctors) { ctor = ct; if (ctor.getGenericParameterTypes().length == 0) break; } if (ctor == null) throw new IllegalStateException("No default constructor found for " + cls.getName()); ctor.setAccessible(true); return ctor; }
3. BridgeUtil#getDefaultConstructor()
Project: bridge
File: BridgeUtil.java
File: BridgeUtil.java
public static Constructor<?> getDefaultConstructor(@NonNull Class<?> cls) { final Constructor[] ctors = cls.getDeclaredConstructors(); Constructor ctor = null; for (Constructor ct : ctors) { ctor = ct; if (ctor.getGenericParameterTypes().length == 0) break; } if (ctor == null) throw new IllegalStateException("No default constructor found for " + cls.getName()); ctor.setAccessible(true); return ctor; }
4. ToothpickTest#constructor_shouldThrowException_whenCalled()
Project: toothpick
File: ToothpickTest.java
File: ToothpickTest.java
@Test(expected = InvocationTargetException.class) public void constructor_shouldThrowException_whenCalled() throws Exception { //GIVEN //WHEN Constructor constructor = Toothpick.class.getDeclaredConstructor(); constructor.setAccessible(true); constructor.newInstance(); //THEN fail("default constructor should not be invokable even via reflection"); }
5. NBTTag#toNMS()
Project: NBTLibrary
File: NBTTag.java
File: NBTTag.java
public Object toNMS() throws ReflectiveOperationException { Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); Constructor constructor = null; for (Constructor constr : clazz.getConstructors()) { if (constr.getParameterTypes().length == 1) { constructor = constr; break; } } if (constructor == null) { return null; } return constructor.newInstance(getValue()); }
6. ReflectionUtils#hasDefaultConstructor()
Project: aries
File: ReflectionUtils.java
File: ReflectionUtils.java
public static boolean hasDefaultConstructor(Class type) { if (!Modifier.isPublic(type.getModifiers())) { return false; } if (Modifier.isAbstract(type.getModifiers())) { return false; } Constructor[] constructors = type.getConstructors(); for (Constructor constructor : constructors) { if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 0) { return true; } } return false; }
7. ReflectionUtils#hasDefaultConstructor()
Project: apache-aries
File: ReflectionUtils.java
File: ReflectionUtils.java
public static boolean hasDefaultConstructor(Class type) { if (!Modifier.isPublic(type.getModifiers())) { return false; } if (Modifier.isAbstract(type.getModifiers())) { return false; } Constructor[] constructors = type.getConstructors(); for (Constructor constructor : constructors) { if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 0) { return true; } } return false; }
8. MetaObjectClass#getDeclaredConstructors()
Project: android-classyshark
File: MetaObjectClass.java
File: MetaObjectClass.java
@Override public ConstructorInfo[] getDeclaredConstructors() { Constructor[] implConstructors = clazz.getDeclaredConstructors(); List<ConstructorInfo> result = new ArrayList<>(); for (Constructor constructor : implConstructors) { ConstructorInfo ci = new ConstructorInfo(); ci.parameterTypes = convertParameters(constructor.getParameterTypes(), constructor.getGenericParameterTypes()); ci.annotations = convertAnnotations(constructor.getAnnotations()); ci.modifiers = constructor.getModifiers(); result.add(ci); } ConstructorInfo[] array = new ConstructorInfo[result.size()]; return result.toArray(array); }
9. TransientStateTest#testHandleMerge()
Project: Kundera
File: TransientStateTest.java
File: TransientStateTest.java
/** * Test method for * {@link com.impetus.kundera.lifecycle.states.TransientState#handleMerge(com.impetus.kundera.lifecycle.NodeStateContext)} * . * * @throws NoSuchMethodException * @throws SecurityException * @throws InvocationTargetException * @throws IllegalAccessException * @throws InstantiationException * @throws IllegalArgumentException */ @Test public void testHandleMerge() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.MERGE); EntityManagerFactory emf = Persistence.createEntityManagerFactory("kunderatest"); Constructor constructor = PersistenceDelegator.class.getDeclaredConstructor(KunderaMetadata.class, PersistenceCache.class); constructor.setAccessible(true); PersistenceDelegator pd = (PersistenceDelegator) constructor.newInstance(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), new PersistenceCache()); storeNode.setPersistenceDelegator(pd); Object data1 = storeNode.getData(); state.handleMerge(storeNode); Object data2 = storeNode.getData(); Assert.assertTrue(DeepEquals.deepEquals(data1, data2)); }
10. TestDateTimeFieldType#test_other()
Project: joda-time
File: TestDateTimeFieldType.java
File: TestDateTimeFieldType.java
public void test_other() throws Exception { assertEquals(1, DateTimeFieldType.class.getDeclaredClasses().length); Class cls = DateTimeFieldType.class.getDeclaredClasses()[0]; assertEquals(1, cls.getDeclaredConstructors().length); Constructor con = cls.getDeclaredConstructors()[0]; Object[] params = new Object[] { "other", new Byte((byte) 128), DurationFieldType.hours(), DurationFieldType.months() }; // for Apache Harmony JVM con.setAccessible(true); DateTimeFieldType type = (DateTimeFieldType) con.newInstance(params); assertEquals("other", type.getName()); assertSame(DurationFieldType.hours(), type.getDurationType()); assertSame(DurationFieldType.months(), type.getRangeDurationType()); try { type.getField(CopticChronology.getInstanceUTC()); fail(); } catch (InternalError ex) { } DateTimeFieldType result = doSerialization(type); assertEquals(type.getName(), result.getName()); assertNotSame(type, result); }
11. TestPlainArrayNotGeneric#checkClass()
Project: jdk7u-jdk
File: TestPlainArrayNotGeneric.java
File: TestPlainArrayNotGeneric.java
private static void checkClass(Class<?> c) throws Exception { Method[] methods = c.getMethods(); for (Method m : methods) { check(m.getGenericReturnType(), "return type of method " + m); check(m.getGenericParameterTypes(), "parameter", "method " + m); check(m.getTypeParameters(), "type parameter", "method " + m); } Constructor[] constructors = c.getConstructors(); for (Constructor constr : constructors) { check(constr.getGenericParameterTypes(), "parameter", "constructor " + constr); check(constr.getTypeParameters(), "type parameter", "constructor " + constr); } Class<?>[] inners = c.getDeclaredClasses(); for (Class inner : inners) checkClass(inner); }
12. ReflectionTest#printConstructors()
Project: java-core-learning-example
File: ReflectionTest.java
File: ReflectionTest.java
/** * ??Class??????? * @param cl */ public static void printConstructors(Class cl) { // ?????????? Constructor[] constructors = cl.getDeclaredConstructors(); for (Constructor c : constructors) { // ???????? String name = c.getName(); System.out.print(" "); // ??Java?????? // ???? Java ???? public?protected?private? // final?static?abstract ? interface ???????? String modifiers = Modifier.toString(c.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.print(name + "("); // ??????????????? Class[] paramTypes = c.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { if (i > 0) System.out.print(", "); System.out.print(paramTypes[i].getName()); } System.out.println(");"); } }
13. SentryIndexAuthorizationSingletonTest#testNoBinding()
Project: incubator-sentry
File: SentryIndexAuthorizationSingletonTest.java
File: SentryIndexAuthorizationSingletonTest.java
@Test public void testNoBinding() throws Exception { // Use reflection to construct a non-singleton version of SentryIndexAuthorizationSingleton // in order to get an instance without a binding Constructor ctor = SentryIndexAuthorizationSingleton.class.getDeclaredConstructor(String.class); ctor.setAccessible(true); SentryIndexAuthorizationSingleton nonSingleton = (SentryIndexAuthorizationSingleton) ctor.newInstance(""); doExpectUnauthorized(nonSingleton, null, null, "binding"); // test getUserName try { nonSingleton.getUserName(null); Assert.fail("Expected Solr exception"); } catch (SolrException ex) { assertEquals(ex.code(), SolrException.ErrorCode.UNAUTHORIZED.code); } Collection<String> groups = nonSingleton.getRoles("junit"); assertEquals(null, groups); }
14. Request2#newInstance()
Project: h2o-2
File: Request2.java
File: Request2.java
private Filter newInstance(API api) throws Exception { for (Constructor c : api.filter().getDeclaredConstructors()) { c.setAccessible(true); Class[] ps = c.getParameterTypes(); if (ps.length == 1 && RequestArguments.class.isAssignableFrom(ps[0])) return (Filter) c.newInstance(this); } for (Constructor c : api.filter().getDeclaredConstructors()) { Class[] ps = c.getParameterTypes(); if (ps.length == 0) return (Filter) c.newInstance(); } throw new Exception("Class " + api.filter().getName() + " must have an empty constructor"); }
15. BytecodeGenTest#testClassLoaderBridging()
Project: guice
File: BytecodeGenTest.java
File: BytecodeGenTest.java
public void testClassLoaderBridging() throws Exception { ClassLoader testClassLoader = new TestVisibilityClassLoader(false); Class hiddenMethodReturnClass = testClassLoader.loadClass(HiddenMethodReturn.class.getName()); Class hiddenMethodParameterClass = testClassLoader.loadClass(HiddenMethodParameter.class.getName()); Injector injector = Guice.createInjector(noopInterceptorModule); Class hiddenClass = testClassLoader.loadClass(Hidden.class.getName()); Constructor ctor = hiddenClass.getDeclaredConstructor(); ctor.setAccessible(true); // don't use bridging for proxies with private parameters Object o1 = injector.getInstance(hiddenMethodParameterClass); o1.getClass().getDeclaredMethod("method", hiddenClass).invoke(o1, ctor.newInstance()); // don't use bridging for proxies with private return types Object o2 = injector.getInstance(hiddenMethodReturnClass); o2.getClass().getDeclaredMethod("method").invoke(o2); }
16. TraitTripleProxyClassBuilderImpl#getPossibleConstructor()
Project: drools
File: TraitTripleProxyClassBuilderImpl.java
File: TraitTripleProxyClassBuilderImpl.java
private Class getPossibleConstructor(Class klass, Class arg) throws NoSuchMethodException { Constructor[] ctors = klass.getConstructors(); for (Constructor c : ctors) { Class[] cpars = c.getParameterTypes(); if (cpars.length != 1 || !cpars[0].isAssignableFrom(arg)) { continue; } return cpars[0]; } throw new NoSuchMethodException("Constructor for " + klass + " using " + arg + " not found "); }
17. TraitMapProxyClassBuilderImpl#getPossibleConstructor()
Project: drools
File: TraitMapProxyClassBuilderImpl.java
File: TraitMapProxyClassBuilderImpl.java
private Class getPossibleConstructor(Class klass, Class arg) throws NoSuchMethodException { Constructor[] ctors = klass.getConstructors(); for (Constructor c : ctors) { Class[] cpars = c.getParameterTypes(); if (cpars.length != 1 || !cpars[0].isAssignableFrom(arg)) { continue; } return cpars[0]; } throw new NoSuchMethodException("Constructor for " + klass + " using " + arg + " not found "); }
18. ApkItem#getResources()
Project: DroidPlugin
File: ApkItem.java
File: ApkItem.java
public static Resources getResources(Context context, String apkPath) throws Exception { String PATH_AssetManager = "android.content.res.AssetManager"; Class assetMagCls = Class.forName(PATH_AssetManager); Constructor assetMagCt = assetMagCls.getConstructor((Class[]) null); Object assetMag = assetMagCt.newInstance((Object[]) null); Class[] typeArgs = new Class[1]; typeArgs[0] = String.class; Method assetMag_addAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath", typeArgs); Object[] valueArgs = new Object[1]; valueArgs[0] = apkPath; assetMag_addAssetPathMtd.invoke(assetMag, valueArgs); Resources res = context.getResources(); typeArgs = new Class[3]; typeArgs[0] = assetMag.getClass(); typeArgs[1] = res.getDisplayMetrics().getClass(); typeArgs[2] = res.getConfiguration().getClass(); Constructor resCt = Resources.class.getConstructor(typeArgs); valueArgs = new Object[3]; valueArgs[0] = assetMag; valueArgs[1] = res.getDisplayMetrics(); valueArgs[2] = res.getConfiguration(); res = (Resources) resCt.newInstance(valueArgs); return res; }
19. Controller#newInstance()
Project: Conductor
File: Controller.java
File: Controller.java
static Controller newInstance(Bundle bundle) { final String className = bundle.getString(KEY_CLASS_NAME); //noinspection ConstantConditions Constructor[] constructors = ClassUtils.classForName(className, false).getConstructors(); Constructor bundleConstructor = getBundleConstructor(constructors); Controller controller; try { if (bundleConstructor != null) { controller = (Controller) bundleConstructor.newInstance(bundle.getBundle(KEY_ARGS)); } else { //noinspection ConstantConditions controller = (Controller) getDefaultConstructor(constructors).newInstance(); } } catch (Exception e) { throw new RuntimeException("An exception occurred while creating a new instance of " + className + ". " + e.getMessage(), e); } controller.restoreInstanceState(bundle); return controller; }
20. Types#lookupConstructor()
Project: calcite
File: Types.java
File: Types.java
/** * Finds a constructor of a given class that accepts a given set of * arguments. Includes in its search methods with wider argument types. * * @param type Class against which method is invoked * @param argumentTypes Types of arguments * * @return A method with the given name that matches the arguments given * @throws RuntimeException if method not found */ public static Constructor lookupConstructor(Type type, Class... argumentTypes) { final Class clazz = toClass(type); Constructor[] constructors = clazz.getDeclaredConstructors(); for (Constructor constructor : constructors) { if (allAssignable(constructor.isVarArgs(), constructor.getParameterTypes(), argumentTypes)) { return constructor; } } if (constructors.length == 0 && argumentTypes.length == 0) { Constructor[] constructors1 = clazz.getConstructors(); try { return clazz.getConstructor(); } catch (NoSuchMethodException e) { } } throw new RuntimeException("while resolving constructor in class " + type + " with types " + Arrays.toString(argumentTypes)); }
21. TimeStampTokenInfoUnitTest#getTimeStampTokenInfo()
Project: bc-java
File: TimeStampTokenInfoUnitTest.java
File: TimeStampTokenInfoUnitTest.java
private TimeStampTokenInfo getTimeStampTokenInfo(byte[] tstInfo) throws Exception { ASN1InputStream aIn = new ASN1InputStream(tstInfo); TSTInfo info = TSTInfo.getInstance(aIn.readObject()); final Constructor constructor = TimeStampTokenInfo.class.getDeclaredConstructor(TSTInfo.class); constructor.setAccessible(true); try { return (TimeStampTokenInfo) constructor.newInstance(new Object[] { info }); } catch (InvocationTargetException e) { throw (Exception) e.getTargetException(); } }
22. Gadgets#makeMap()
Project: ysoserial
File: Gadgets.java
File: Gadgets.java
public static HashMap makeMap(Object v1, Object v2) throws Exception, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { HashMap s = new HashMap(); Reflections.setFieldValue(s, "size", 2); Class nodeC; try { nodeC = Class.forName("java.util.HashMap$Node"); } catch (ClassNotFoundException e) { nodeC = Class.forName("java.util.HashMap$Entry"); } Constructor nodeCons = nodeC.getDeclaredConstructor(int.class, Object.class, Object.class, nodeC); nodeCons.setAccessible(true); Object tbl = Array.newInstance(nodeC, 2); Array.set(tbl, 0, nodeCons.newInstance(0, v1, v1, null)); Array.set(tbl, 1, nodeCons.newInstance(0, v2, v2, null)); Reflections.setFieldValue(s, "table", tbl); return s; }
23. ToStringChecker#createObject()
Project: storio
File: ToStringChecker.java
File: ToStringChecker.java
@NonNull private T createObject() { Constructor[] constructors = clazz.getDeclaredConstructors(); for (Constructor constructor : constructors) { try { constructor.setAccessible(true); List<Object> sampleParameters = new ArrayList<Object>(); for (Class parameterType : constructor.getParameterTypes()) { sampleParameters.add(createSampleValueOfType(parameterType)); } //noinspection unchecked return (T) constructor.newInstance(sampleParameters.toArray()); } catch (Exception uh) { } } throw new IllegalStateException("Tried all declared constructors, no luck :("); }
24. ReflectionsTest#test_constructor_with_params()
Project: smart-adapters
File: ReflectionsTest.java
File: ReflectionsTest.java
@Test public void test_constructor_with_params() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { SomeModel byHandModel = new SomeModel(1); Constructor constructor = Reflections.constructor(SomeModel.class, int.class); SomeModel autoModel = (SomeModel) constructor.newInstance(1); assertEquals(byHandModel, autoModel); // Check the caching and clashing with other constructors Reflections.constructor(SomeModel.class); Constructor constructor2 = Reflections.constructor(SomeModel.class, int.class); assertEquals(constructor, constructor2); }
25. SentryIndexAuthorizationSingletonTest#testNoBinding()
Project: sentry
File: SentryIndexAuthorizationSingletonTest.java
File: SentryIndexAuthorizationSingletonTest.java
@Test public void testNoBinding() throws Exception { // Use reflection to construct a non-singleton version of SentryIndexAuthorizationSingleton // in order to get an instance without a binding Constructor ctor = SentryIndexAuthorizationSingleton.class.getDeclaredConstructor(String.class); ctor.setAccessible(true); SentryIndexAuthorizationSingleton nonSingleton = (SentryIndexAuthorizationSingleton) ctor.newInstance(""); doExpectUnauthorized(nonSingleton, null, null, "binding"); // test getUserName try { nonSingleton.getUserName(null); Assert.fail("Expected Solr exception"); } catch (SolrException ex) { assertEquals(ex.code(), SolrException.ErrorCode.UNAUTHORIZED.code); } Collection<String> groups = nonSingleton.getRoles("junit"); assertEquals(null, groups); }
26. BleConnectionCompat#createBluetoothGatt()
Project: RxAndroidBle
File: BleConnectionCompat.java
File: BleConnectionCompat.java
@TargetApi(Build.VERSION_CODES.M) private BluetoothGatt createBluetoothGatt(Object iBluetoothGatt, BluetoothDevice remoteDevice) throws IllegalAccessException, InvocationTargetException, InstantiationException { Constructor bluetoothGattConstructor = BluetoothGatt.class.getDeclaredConstructors()[0]; bluetoothGattConstructor.setAccessible(true); RxBleLog.v("Found constructor with args count = " + bluetoothGattConstructor.getParameterTypes().length); if (bluetoothGattConstructor.getParameterTypes().length == 4) { return (BluetoothGatt) (bluetoothGattConstructor.newInstance(context, iBluetoothGatt, remoteDevice, TRANSPORT_LE)); } else { return (BluetoothGatt) (bluetoothGattConstructor.newInstance(context, iBluetoothGatt, remoteDevice)); } }
27. TestPlainArrayNotGeneric#checkClass()
Project: openjdk
File: TestPlainArrayNotGeneric.java
File: TestPlainArrayNotGeneric.java
private static void checkClass(Class<?> c) throws Exception { Method[] methods = c.getMethods(); for (Method m : methods) { check(m.getGenericReturnType(), "return type of method " + m); check(m.getGenericParameterTypes(), "parameter", "method " + m); check(m.getTypeParameters(), "type parameter", "method " + m); } Constructor[] constructors = c.getConstructors(); for (Constructor constr : constructors) { check(constr.getGenericParameterTypes(), "parameter", "constructor " + constr); check(constr.getTypeParameters(), "type parameter", "constructor " + constr); } Class<?>[] inners = c.getDeclaredClasses(); for (Class inner : inners) checkClass(inner); }
28. ParseTools#getBestConstructorCandidate()
Project: mvel
File: ParseTools.java
File: ParseTools.java
public static Constructor getBestConstructorCandidate(Class[] arguments, Class cls, boolean requireExact) { Class[] parmTypes; Constructor bestCandidate = null; int bestScore = 0; for (Constructor construct : getConstructors(cls)) { boolean isVarArgs = construct.isVarArgs(); if ((parmTypes = getConstructors(construct)).length != arguments.length && !construct.isVarArgs()) { continue; } else if (arguments.length == 0 && parmTypes.length == 0) { return construct; } int score = getMethodScore(arguments, requireExact, parmTypes, isVarArgs); if (score != 0 && score > bestScore) { bestCandidate = construct; bestScore = score; } } return bestCandidate; }
29. Spring1#getObject()
Project: ysoserial
File: Spring1.java
File: Spring1.java
public Object getObject(final String command) throws Exception { final Object templates = Gadgets.createTemplatesImpl(command); final ObjectFactory objectFactoryProxy = Gadgets.createMemoitizedProxy(Gadgets.createMap("getObject", templates), ObjectFactory.class); final Type typeTemplatesProxy = Gadgets.createProxy((InvocationHandler) Reflections.getFirstCtor("org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler").newInstance(objectFactoryProxy), Type.class, Templates.class); final Object typeProviderProxy = Gadgets.createMemoitizedProxy(Gadgets.createMap("getType", typeTemplatesProxy), forName("org.springframework.core.SerializableTypeWrapper$TypeProvider")); final Constructor mitpCtor = Reflections.getFirstCtor("org.springframework.core.SerializableTypeWrapper$MethodInvokeTypeProvider"); final Object mitp = mitpCtor.newInstance(typeProviderProxy, Object.class.getMethod("getClass", new Class[] {}), 0); Reflections.setFieldValue(mitp, "methodName", "newTransformer"); return mitp; }
30. HibernateCollectionsTypeCompatibilityTest#newHibernateCollection()
Project: xstream
File: HibernateCollectionsTypeCompatibilityTest.java
File: HibernateCollectionsTypeCompatibilityTest.java
private Object newHibernateCollection(Class type, Object secondArg) { Object instance = null; Constructor[] ctors = type.getConstructors(); for (int i = 0; i < ctors.length; ++i) { if (ctors[i].getParameterTypes().length == 2) { try { instance = ctors[i].newInstance(new Object[] { null, secondArg }); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } break; } } assertNotNull(instance); return instance; }
31. ReflectionClassesTest#testReflectionConstructor()
Project: xstream
File: ReflectionClassesTest.java
File: ReflectionClassesTest.java
public void testReflectionConstructor() throws NoSuchMethodException { Constructor constructor = StupidObject.class.getConstructor(new Class[] { String.class }); String expected = "<constructor>\n" + " <class>com.thoughtworks.acceptance.ReflectionClassesTest$StupidObject</class>\n" + " <parameter-types>\n" + " <class>java.lang.String</class>\n" + " </parameter-types>\n" + "</constructor>"; assertBothWays(constructor, expected); }
32. ImporterTest#doTest()
Project: voxelshop
File: ImporterTest.java
File: ImporterTest.java
// load all files in directory private void doTest(String directory, String ext, Class importerClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { File[] files = FileTools.findFiles(directory, ext); @SuppressWarnings("unchecked") Constructor ctor = importerClass.getConstructor(File.class, String.class); for (File file : files) { System.out.print("Checking " + file.getName() + "... "); AbstractImporter importer = (AbstractImporter) ctor.newInstance(file, "Import"); assert importer.hasLoaded(); for (AbstractImporter.Layer layer : importer.getVoxel()) { assert !layer.isEmpty(); } System.out.println("ok."); } }
33. SpringContextResourceManager#newInstance()
Project: uima-uimafit
File: SpringContextResourceManager.java
File: SpringContextResourceManager.java
/** * Instantiate a non-visible class. */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> T newInstance(String aClassName, Object... aArgs) throws ResourceInitializationException { Constructor constr = null; try { Class<?> cl = Class.forName(aClassName); List<Class> types = new ArrayList<Class>(); List<Object> values = new ArrayList<Object>(); for (int i = 0; i < aArgs.length; i += 2) { types.add((Class) aArgs[i]); values.add(aArgs[i + 1]); } constr = cl.getDeclaredConstructor(types.toArray(new Class[types.size()])); constr.setAccessible(true); return (T) constr.newInstance(values.toArray(new Object[values.size()])); } catch (Exception e) { throw new ResourceInitializationException(e); } finally { if (constr != null) { constr.setAccessible(false); } } }
34. SimpleNamedResourceManager#newInstance()
Project: uima-uimafit
File: SimpleNamedResourceManager.java
File: SimpleNamedResourceManager.java
/** * Instantiate a non-visible class. */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> T newInstance(String aClassName, Object... aArgs) throws ResourceInitializationException { Constructor constr = null; try { Class<?> cl = Class.forName(aClassName); List<Class> types = new ArrayList<Class>(); List<Object> values = new ArrayList<Object>(); for (int i = 0; i < aArgs.length; i += 2) { types.add((Class) aArgs[i]); values.add(aArgs[i + 1]); } constr = cl.getDeclaredConstructor(types.toArray(new Class[types.size()])); constr.setAccessible(true); return (T) constr.newInstance(values.toArray(new Object[values.size()])); } catch (Exception e) { throw new ResourceInitializationException(e); } finally { if (constr != null) { constr.setAccessible(false); } } }
35. InjectionPointFactoryTest#testConstructorInjectionPointBuild()
Project: transfuse
File: InjectionPointFactoryTest.java
File: InjectionPointFactoryTest.java
@Test public void testConstructorInjectionPointBuild() { Constructor<?>[] constructors = MockAnalysisClass.class.getConstructors(); Constructor constructor = constructors[0]; ConstructorInjectionPoint constructorInjectionPoint = injectionPointFactory.buildInjectionPoint(astClassFactory.getType(MockAnalysisClass.class), astClassFactory.getConstructor(constructor, false, false), emptyContext); TypeVariable[] typeParameters = constructor.getTypeParameters(); List<InjectionNode> injectionNodes = constructorInjectionPoint.getInjectionNodes(); for (int i = 0; i < typeParameters.length; i++) { InjectionNode injectionNode = injectionNodes.get(i); TypeVariable typeParameter = typeParameters[i]; assertEquals(typeParameter.getName(), injectionNode.getClassName()); } assertEquals(1, constructorInjectionPoint.getThrowsTypes().size()); assertEquals(astClassFactory.getType(TransfuseInjectionException.class), constructorInjectionPoint.getThrowsTypes().get(0)); }
36. MAnnotationSampleTest#verifyTestConstructorLevel()
Project: testng
File: MAnnotationSampleTest.java
File: MAnnotationSampleTest.java
public void verifyTestConstructorLevel() throws SecurityException, NoSuchMethodException { // // Tests on MTest1SampleTest // Constructor constructor = MTest1.class.getConstructor(new Class[0]); ITestAnnotation test1 = (ITestAnnotation) m_finder.findAnnotation(constructor, ITestAnnotation.class); Assert.assertNotNull(test1); Assert.assertTrue(test1.getEnabled()); Assert.assertEqualsNoOrder(test1.getGroups(), new String[] { "group5", "group1", "group6", "group2" }); Assert.assertTrue(test1.getAlwaysRun()); Assert.assertEquals(test1.getParameters(), new String[] { "param5", "param6" }); Assert.assertEqualsNoOrder(test1.getDependsOnGroups(), new String[] { "dg1", "dg2", "dg5", "dg6" }); Assert.assertEqualsNoOrder(test1.getDependsOnMethods(), new String[] { "dm1", "dm2", "dm5", "dm6" }); Assert.assertEquals(test1.getTimeOut(), 242); Assert.assertEquals(test1.getInvocationCount(), 243); Assert.assertEquals(test1.getSuccessPercentage(), 62); Assert.assertEquals(test1.getDataProvider(), "dp3"); Assert.assertEquals(test1.getDescription(), "Constructor description"); Class[] exceptions = test1.getExpectedExceptions(); Assert.assertEquals(exceptions.length, 1); Assert.assertEquals(exceptions[0], NumberFormatException.class); }
37. JUnitMethodFinder#instantiate()
Project: testng
File: JUnitMethodFinder.java
File: JUnitMethodFinder.java
private Object instantiate(Class cls) { Object result = null; Constructor ctor = findConstructor(cls, new Class[] { String.class }); try { if (null != ctor) { result = ctor.newInstance(new Object[] { m_testName }); } else { ctor = cls.getConstructor(new Class[0]); result = ctor.newInstance(new Object[0]); } } catch (IllegalArgumentExceptionNoSuchMethodException | InvocationTargetException | IllegalAccessException | SecurityException | ex) { ex.printStackTrace(); } catch (InstantiationException ex) { System.err.println("Couldn't find a constructor with a String parameter on your JUnit test class."); ex.printStackTrace(); } return result; }
38. JUnitMethodFinder#findConstructor()
Project: testng
File: JUnitMethodFinder.java
File: JUnitMethodFinder.java
private Constructor findConstructor(Class cls, Class[] parameters) { Constructor result = null; try { result = cls.getConstructor(parameters); } catch (SecurityExceptionNoSuchMethodException | ex) { } return result; }
39. InternalUtilsTest#validate_constructor_check_for_public()
Project: tapestry5
File: InternalUtilsTest.java
File: InternalUtilsTest.java
@Test public void validate_constructor_check_for_public() { Class clazz = PublicInnerClass.class; Constructor cons = clazz.getDeclaredConstructors()[0]; try { InternalUtils.validateConstructorForAutobuild(cons); unreachable(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "Constructor protected org.apache.tapestry5.ioc.internal.util.InternalUtilsTest$PublicInnerClass() is not public and may not be used for autobuilding an instance of the class."); } }
40. InternalUtilsTest#validate_constructor_class_not_public()
Project: tapestry5
File: InternalUtilsTest.java
File: InternalUtilsTest.java
@Test public void validate_constructor_class_not_public() { Class clazz = PrivateInnerClass.class; Constructor cons = clazz.getConstructors()[0]; try { InternalUtils.validateConstructorForAutobuild(cons); unreachable(); } catch (IllegalArgumentException ex) { assertEquals(ex.getMessage(), "Class org.apache.tapestry5.ioc.internal.util.InternalUtilsTest$PrivateInnerClass is not a public class and may not be autobuilt."); } }
41. ClassFactoryImplTest#get_constructor_location()
Project: tapestry5
File: ClassFactoryImplTest.java
File: ClassFactoryImplTest.java
@Test public void get_constructor_location() throws Exception { Constructor cc = LineNumberBean.class.getConstructors()[0]; ClassFactory factory = new ClassFactoryImpl(); // Eclipse and Sun JDK don't agree on the line number, so we'll accept either. assertTrue(factory.getConstructorLocation(cc).toString().matches("org.apache.tapestry5.ioc.internal.services.LineNumberBean\\(String, int\\) \\(at LineNumberBean.java:(19|20)\\)")); }
42. ClassFabImplTest#add_constructor_from_base_class()
Project: tapestry5
File: ClassFabImplTest.java
File: ClassFabImplTest.java
@Test public void add_constructor_from_base_class() throws Exception { ClassFab cf = newClassFab("MyIntHolder", AbstractIntWrapper.class); cf.addField("_intValue", int.class); cf.addConstructor(new Class[] { int.class }, null, "{ _intValue = $1; }"); cf.addMethod(Modifier.PUBLIC, new MethodSignature(int.class, "getIntValue", null, null), "return _intValue;"); Class targetClass = cf.createClass(); Constructor c = targetClass.getConstructors()[0]; AbstractIntWrapper targetBean = (AbstractIntWrapper) c.newInstance(new Object[] { new Integer(137) }); assertEquals(targetBean.getIntValue(), 137); }
43. ServiceResourcesImpl#autobuild()
Project: tapestry5
File: ServiceResourcesImpl.java
File: ServiceResourcesImpl.java
@Override public <T> T autobuild(Class<T> clazz) { notNull(clazz, "clazz"); Constructor constructor = InternalUtils.findAutobuildConstructor(clazz); if (constructor == null) throw new RuntimeException(IOCMessages.noAutobuildConstructor(clazz)); String description = classFactory.getConstructorLocation(constructor).toString(); ObjectCreator creator = new ConstructorServiceCreator(this, description, constructor); return clazz.cast(creator.createObject()); }
44. ServiceBinderImpl#createObjectCreatorSourceFromImplementationClass()
Project: tapestry5
File: ServiceBinderImpl.java
File: ServiceBinderImpl.java
private ObjectCreatorSource createObjectCreatorSourceFromImplementationClass() { final Constructor constructor = InternalUtils.findAutobuildConstructor(serviceImplementation); if (constructor == null) throw new RuntimeException(IOCMessages.noConstructor(serviceImplementation, serviceId)); return new ObjectCreatorSource() { public ObjectCreator constructCreator(ServiceBuilderResources resources) { return new ConstructorServiceCreator(resources, getDescription(), constructor); } public String getDescription() { return String.format("%s via %s", classFactory.getConstructorLocation(constructor), classFactory.getMethodLocation(bindMethod)); } }; }
45. ServiceBinderImpl#createStandardConstructorBasedObjectCreatorSource()
Project: tapestry-5
File: ServiceBinderImpl.java
File: ServiceBinderImpl.java
private ObjectCreatorSource createStandardConstructorBasedObjectCreatorSource() { if (Modifier.isAbstract(serviceImplementation.getModifiers())) throw new RuntimeException(IOCMessages.abstractServiceImplementation(serviceImplementation, serviceId)); final Constructor constructor = InternalUtils.findAutobuildConstructor(serviceImplementation); if (constructor == null) throw new RuntimeException(IOCMessages.noConstructor(serviceImplementation, serviceId)); return new ObjectCreatorSource() { @Override public ObjectCreator constructCreator(ServiceBuilderResources resources) { return new ConstructorServiceCreator(resources, getDescription(), constructor); } @Override public String getDescription() { return String.format("%s via %s", proxyFactory.getConstructorLocation(constructor), proxyFactory.getMethodLocation(bindMethod)); } }; }
46. ReloadableServiceImplementationObjectCreator#createInstance()
Project: tapestry-5
File: ReloadableServiceImplementationObjectCreator.java
File: ReloadableServiceImplementationObjectCreator.java
@Override protected Object createInstance(Class clazz) { final Constructor constructor = InternalUtils.findAutobuildConstructor(clazz); if (constructor == null) throw new RuntimeException(String.format("Service implementation class %s does not have a suitable public constructor.", clazz.getName())); ObjectCreator constructorServiceCreator = new ConstructorServiceCreator(resources, constructor.toString(), constructor); return constructorServiceCreator.createObject(); }
47. RegistryImpl#autobuild()
Project: tapestry-5
File: RegistryImpl.java
File: RegistryImpl.java
@Override public <T> T autobuild(final Class<T> clazz) { assert clazz != null; final Constructor constructor = InternalUtils.findAutobuildConstructor(clazz); if (constructor == null) { throw new RuntimeException(IOCMessages.noAutobuildConstructor(clazz)); } Map<Class, Object> resourcesMap = CollectionFactory.newMap(); resourcesMap.put(OperationTracker.class, RegistryImpl.this); InjectionResources resources = new MapInjectionResources(resourcesMap); ObjectCreator<T> plan = InternalUtils.createConstructorConstructionPlan(this, this, resources, null, "Invoking " + proxyFactory.getConstructorLocation(constructor).toString(), constructor); return plan.createObject(); }
48. Hex#getProtectedConstructor()
Project: stratio-cassandra
File: Hex.java
File: Hex.java
/** * Used to get access to protected/private constructor of the specified class * @param klass - name of the class * @param paramTypes - types of the constructor parameters * @return Constructor if successful, null if the constructor cannot be * accessed */ public static Constructor getProtectedConstructor(Class klass, Class... paramTypes) { Constructor c; try { c = klass.getDeclaredConstructor(paramTypes); c.setAccessible(true); return c; } catch (Exception e) { return null; } }
49. PagedResultsRequestControl#createRequestControl()
Project: spring-ldap
File: PagedResultsRequestControl.java
File: PagedResultsRequestControl.java
/* * @see * org.springframework.ldap.control.AbstractRequestControlDirContextProcessor * #createRequestControl() */ public Control createRequestControl() { byte[] actualCookie = null; if (cookie != null) { actualCookie = cookie.getCookie(); } Constructor constructor = ClassUtils.getConstructorIfAvailable(requestControlClass, new Class[] { int.class, byte[].class, boolean.class }); if (constructor == null) { throw new IllegalArgumentException("Failed to find an appropriate RequestControl constructor"); } Control result = null; try { result = (Control) constructor.newInstance(pageSize, actualCookie, critical); } catch (Exception e) { ReflectionUtils.handleReflectionException(e); } return result; }
50. TestUtil#processComponent()
Project: spacewalk
File: TestUtil.java
File: TestUtil.java
@SuppressWarnings("unchecked") private static List<Class> processComponent(Class component, List<Class> accum) { if (component == Configuration.class) { return accum; } if (accum.indexOf(component) == -1) { accum.add(component); } Constructor[] constructors = component.getConstructors(); if (constructors != null) { for (int x = 0; x < constructors.length; x++) { Class[] paramTypes = constructors[x].getParameterTypes(); if (paramTypes.length > 0) { for (int y = 0; y < paramTypes.length; y++) { if (isCandidate(paramTypes[y].getName())) { processComponent(paramTypes[y], accum); } } } } } return accum; }
51. TestUtils#hasOnlyPrivateConstructors()
Project: sonarqube
File: TestUtils.java
File: TestUtils.java
/** * Asserts that all constructors are private, usually for helper classes with * only static methods. If a constructor does not have any parameters, then * it's instantiated. */ public static boolean hasOnlyPrivateConstructors(Class clazz) { boolean ok = true; for (Constructor constructor : clazz.getDeclaredConstructors()) { ok &= Modifier.isPrivate(constructor.getModifiers()); if (constructor.getParameterTypes().length == 0) { constructor.setAccessible(true); try { constructor.newInstance(); } catch (Exception e) { throw new IllegalStateException(String.format("Fail to instantiate %s", clazz), e); } } } return ok; }
52. ProxyFactory#makeConstructors()
Project: scouter
File: ProxyFactory.java
File: ProxyFactory.java
private void makeConstructors(String thisClassName, ClassFile cf, ConstPool cp, String classname) throws CannotCompileException { Constructor[] cons = SecurityActions.getDeclaredConstructors(superClass); // legacy: if we are not caching then we need to initialise the default handler boolean doHandlerInit = !factoryUseCache; for (int i = 0; i < cons.length; i++) { Constructor c = cons[i]; int mod = c.getModifiers(); if (!Modifier.isFinal(mod) && !Modifier.isPrivate(mod) && isVisible(mod, basename, c)) { MethodInfo m = makeConstructor(thisClassName, c, cp, superClass, doHandlerInit); cf.addMethod(m); } } }
53. ShadowWrangler#findConstructor()
Project: robolectric
File: ShadowWrangler.java
File: ShadowWrangler.java
private Constructor<?> findConstructor(Object instance, Class<?> shadowClass) { Class clazz = instance.getClass(); Constructor constructor; for (constructor = null; constructor == null && clazz != null; clazz = clazz.getSuperclass()) { try { constructor = shadowClass.getConstructor(clazz); } catch (NoSuchMethodException e) { } } return constructor; }
54. ResourceBuilder#constructor()
Project: Resteasy
File: ResourceBuilder.java
File: ResourceBuilder.java
/** * Picks a constructor from an annotated resource class based on spec rules * * @param annotatedResourceClass * @return */ public static ResourceConstructor constructor(Class<?> annotatedResourceClass) { Constructor constructor = PickConstructor.pickPerRequestConstructor(annotatedResourceClass); if (constructor == null) { throw new RuntimeException(Messages.MESSAGES.couldNotFindConstructor(annotatedResourceClass.getName())); } ResourceConstructorBuilder builder = rootResource(annotatedResourceClass).constructor(constructor); if (constructor.getParameterTypes() != null) { for (int i = 0; i < constructor.getParameterTypes().length; i++) builder.param(i).fromAnnotations(); } return builder.buildConstructor().buildClass().getConstructor(); }
55. WeakConstructorStorage#storeArgs()
Project: railo
File: WeakConstructorStorage.java
File: WeakConstructorStorage.java
/** * seperate and store the different arguments of one constructor * @param constructor * @param conArgs */ private void storeArgs(Constructor constructor, Array conArgs) { Class[] pmt = constructor.getParameterTypes(); Object o = conArgs.get(pmt.length + 1, null); Constructor[] args; if (o == null) { args = new Constructor[1]; conArgs.setEL(pmt.length + 1, args); } else { Constructor[] cs = (Constructor[]) o; args = new Constructor[cs.length + 1]; for (int i = 0; i < cs.length; i++) { args[i] = cs[i]; } conArgs.setEL(pmt.length + 1, args); } args[args.length - 1] = constructor; }
56. ExtendedStackTrace#getMethods()
Project: quasar
File: ExtendedStackTrace.java
File: ExtendedStackTrace.java
protected final Member[] getMethods(Class<?> clazz) { // synchronized (this) { Member[] es; // if (methods == null) // methods = new HashMap<>(); // es = methods.get(clazz); // if (es == null) { Method[] ms = clazz.getDeclaredMethods(); Constructor[] cs = clazz.getDeclaredConstructors(); es = new Member[ms.length + cs.length]; System.arraycopy(cs, 0, es, 0, cs.length); System.arraycopy(ms, 0, es, cs.length, ms.length); // } return es; // } }
57. ReflectionTest#test()
Project: pinpoint
File: ReflectionTest.java
File: ReflectionTest.java
@Test public void test() throws NotFoundException { Constructor<?>[] constructors = String.class.getConstructors(); for (Constructor c : constructors) { logger.debug(c.getName()); } CtClass ctClass = pool.get("java.lang.String"); CtConstructor[] constructors1 = ctClass.getConstructors(); for (CtConstructor cc : constructors1) { logger.debug(cc.getName()); logger.debug(cc.getLongName()); logger.debug(cc.getSignature()); } }
58. VMBridge_jdk13#getInterfaceProxyHelper()
Project: pad
File: VMBridge_jdk13.java
File: VMBridge_jdk13.java
protected Object getInterfaceProxyHelper(ContextFactory cf, Class[] interfaces) { // XXX: How to handle interfaces array withclasses from different // class loaders? Using cf.getApplicationClassLoader() ? ClassLoader loader = interfaces[0].getClassLoader(); Class cl = Proxy.getProxyClass(loader, interfaces); Constructor c; try { c = cl.getConstructor(new Class[] { InvocationHandler.class }); } catch (NoSuchMethodException ex) { throw Kit.initCause(new IllegalStateException(), ex); } return c; }
59. ArbitrateFactory#newInstance()
Project: otter
File: ArbitrateFactory.java
File: ArbitrateFactory.java
// ==================== helper method ======================= private static Object newInstance(Class type, Long pipelineId) { Constructor _constructor = null; Object[] _constructorArgs = new Object[1]; _constructorArgs[0] = pipelineId; try { _constructor = type.getConstructor(new Class[] { Long.class }); } catch (NoSuchMethodException e) { throw new ArbitrateException("Constructor_notFound"); } try { return _constructor.newInstance(_constructorArgs); } catch (Exception e) { throw new ArbitrateException("Constructor_newInstance_error", e); } }
60. RelJson#getConstructor()
Project: optiq
File: RelJson.java
File: RelJson.java
public Constructor getConstructor(String type) { Constructor constructor = constructorMap.get(type); if (constructor == null) { Class clazz = typeNameToClass(type); try { //noinspection unchecked constructor = clazz.getConstructor(RelInput.class); } catch (NoSuchMethodException e) { throw new RuntimeException("class does not have required constructor, " + clazz + "(RelInput)"); } constructorMap.put(type, constructor); } return constructor; }
61. RelJson#create()
Project: optiq
File: RelJson.java
File: RelJson.java
public RelNode create(Map<String, Object> map) { String type = (String) map.get("type"); Constructor constructor = getConstructor(type); try { return (RelNode) constructor.newInstance(map); } catch (InstantiationException e) { throw new RuntimeException("while invoking constructor for type '" + type + "'", e); } catch (IllegalAccessException e) { throw new RuntimeException("while invoking constructor for type '" + type + "'", e); } catch (InvocationTargetException e) { throw new RuntimeException("while invoking constructor for type '" + type + "'", e); } catch (ClassCastException e) { throw new RuntimeException("while invoking constructor for type '" + type + "'", e); } }
62. ProxyArrays#genArrays()
Project: openjdk
File: ProxyArrays.java
File: ProxyArrays.java
/** * Generate proxy arrays. */ Proxy[][] genArrays(int size, int narrays) throws Exception { Class proxyClass = Proxy.getProxyClass(DummyInterface.class.getClassLoader(), new Class[] { DummyInterface.class }); Constructor proxyCons = proxyClass.getConstructor(new Class[] { InvocationHandler.class }); Object[] consArgs = new Object[] { new DummyHandler() }; Proxy[][] arrays = new Proxy[narrays][size]; for (int i = 0; i < narrays; i++) { for (int j = 0; j < size; j++) { arrays[i][j] = (Proxy) proxyCons.newInstance(consArgs); } } return arrays; }
63. ProxyArrayCalls#genProxies()
Project: openjdk
File: ProxyArrayCalls.java
File: ProxyArrayCalls.java
/** * Generate proxy object array of the given size. */ Proxy[] genProxies(int size) throws Exception { Class proxyClass = Proxy.getProxyClass(DummyInterface.class.getClassLoader(), new Class[] { DummyInterface.class }); Constructor proxyCons = proxyClass.getConstructor(new Class[] { InvocationHandler.class }); Object[] consArgs = new Object[] { new DummyHandler() }; Proxy[] proxies = new Proxy[size]; for (int i = 0; i < size; i++) proxies[i] = (Proxy) proxyCons.newInstance(consArgs); return proxies; }
64. ParseTools#getConstructors()
Project: mvel
File: ParseTools.java
File: ParseTools.java
public static Constructor[] getConstructors(Class cls) { WeakReference<Constructor[]> ref = CLASS_CONSTRUCTOR_CACHE.get(cls); Constructor[] cns; if (ref != null && (cns = ref.get()) != null) { return cns; } else { CLASS_CONSTRUCTOR_CACHE.put(cls, new WeakReference<Constructor[]>(cns = cls.getConstructors())); return cns; } }
65. ModelReader#constructFactor()
Project: Mallet
File: ModelReader.java
File: ModelReader.java
private Factor constructFactor(String[] fields, int idx) { Class factorClass = determineFactorClass(fields, idx); Object[] args = determineFactorArgs(fields, idx); Constructor factorCtor = findCtor(factorClass, args); Factor factor; try { factor = (Factor) factorCtor.newInstance(args); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } return factor; }
66. QueryResolver#getQuery()
Project: Kundera
File: QueryResolver.java
File: QueryResolver.java
/** * Gets the query instance. * * @param jpaQuery * the jpa query * @param persistenceDelegator * the persistence delegator * @param persistenceUnits * the persistence units * @return the query * @throws ClassNotFoundException * the class not found exception * @throws SecurityException * the security exception * @throws NoSuchMethodException * the no such method exception * @throws IllegalArgumentException * the illegal argument exception * @throws InstantiationException * the instantiation exception * @throws IllegalAccessException * the illegal access exception * @throws InvocationTargetException * the invocation target exception */ private Query getQuery(String jpaQuery, PersistenceDelegator persistenceDelegator, EntityMetadata m, KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Query query; Class clazz = persistenceDelegator.getClient(m).getQueryImplementor(); @SuppressWarnings("rawtypes") Constructor constructor = clazz.getConstructor(KunderaQuery.class, PersistenceDelegator.class, KunderaMetadata.class); query = (Query) constructor.newInstance(kunderaQuery, persistenceDelegator, kunderaMetadata); return query; }
67. Ctors#inspectConstructors()
Project: jodd
File: Ctors.java
File: Ctors.java
/** * Inspects all declared constructors of a target type. */ protected CtorDescriptor[] inspectConstructors() { Class type = classDescriptor.getType(); Constructor[] ctors = type.getDeclaredConstructors(); CtorDescriptor[] allCtors = new CtorDescriptor[ctors.length]; for (int i = 0; i < ctors.length; i++) { Constructor ctor = ctors[i]; CtorDescriptor ctorDescriptor = createCtorDescriptor(ctor); allCtors[i] = ctorDescriptor; if (ctorDescriptor.isDefault()) { defaultCtor = ctorDescriptor; } } return allCtors; }
68. TestDurationFieldType#test_other()
Project: joda-time
File: TestDurationFieldType.java
File: TestDurationFieldType.java
public void test_other() throws Exception { assertEquals(1, DurationFieldType.class.getDeclaredClasses().length); Class cls = DurationFieldType.class.getDeclaredClasses()[0]; assertEquals(1, cls.getDeclaredConstructors().length); Constructor con = cls.getDeclaredConstructors()[0]; Object[] params = new Object[] { "other", new Byte((byte) 128) }; DurationFieldType type = (DurationFieldType) con.newInstance(params); assertEquals("other", type.getName()); try { type.getField(CopticChronology.getInstanceUTC()); fail(); } catch (InternalError ex) { } DurationFieldType result = doSerialization(type); assertEquals(type.getName(), result.getName()); assertNotSame(type, result); }
69. TestStringConverter#testSingleton()
Project: joda-time
File: TestStringConverter.java
File: TestStringConverter.java
//----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = StringConverter.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())); }
70. TestReadablePeriodConverter#testSingleton()
Project: joda-time
File: TestReadablePeriodConverter.java
File: TestReadablePeriodConverter.java
//----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ReadablePeriodConverter.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())); }
71. TestReadablePartialConverter#testSingleton()
Project: joda-time
File: TestReadablePartialConverter.java
File: TestReadablePartialConverter.java
//----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ReadablePartialConverter.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())); }
72. TestReadableIntervalConverter#testSingleton()
Project: joda-time
File: TestReadableIntervalConverter.java
File: TestReadableIntervalConverter.java
//----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ReadableIntervalConverter.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())); }
73. TestReadableInstantConverter#testSingleton()
Project: joda-time
File: TestReadableInstantConverter.java
File: TestReadableInstantConverter.java
//----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ReadableInstantConverter.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())); }
74. TestReadableDurationConverter#testSingleton()
Project: joda-time
File: TestReadableDurationConverter.java
File: TestReadableDurationConverter.java
//----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ReadableDurationConverter.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())); }
75. TestNullConverter#testSingleton()
Project: joda-time
File: TestNullConverter.java
File: TestNullConverter.java
//----------------------------------------------------------------------- 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())); }
76. TestLongConverter#testSingleton()
Project: joda-time
File: TestLongConverter.java
File: TestLongConverter.java
//----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = LongConverter.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())); }
77. TestDateConverter#testSingleton()
Project: joda-time
File: TestDateConverter.java
File: TestDateConverter.java
//----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = DateConverter.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())); }
78. TestConverterSet#testClass()
Project: joda-time
File: TestConverterSet.java
File: TestConverterSet.java
//----------------------------------------------------------------------- public void testClass() throws Exception { Class cls = ConverterSet.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); assertEquals(1, cls.getDeclaredConstructors().length); Constructor con = cls.getDeclaredConstructors()[0]; assertEquals(false, Modifier.isPublic(con.getModifiers())); assertEquals(false, Modifier.isProtected(con.getModifiers())); assertEquals(false, Modifier.isPrivate(con.getModifiers())); }
79. TestCalendarConverter#testSingleton()
Project: joda-time
File: TestCalendarConverter.java
File: TestCalendarConverter.java
//----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = CalendarConverter.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())); }
80. Spring1#getObject()
Project: Jenkins2
File: Spring1.java
File: Spring1.java
public Object getObject(final String command) throws Exception { final TemplatesImpl templates = Gadgets.createTemplatesImpl(command); final ObjectFactory objectFactoryProxy = Gadgets.createMemoitizedProxy(Gadgets.createMap("getObject", templates), ObjectFactory.class); final Type typeTemplatesProxy = Gadgets.createProxy((InvocationHandler) Reflections.getFirstCtor("org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler").newInstance(objectFactoryProxy), Type.class, Templates.class); final Object typeProviderProxy = Gadgets.createMemoitizedProxy(Gadgets.createMap("getType", typeTemplatesProxy), forName("org.springframework.core.SerializableTypeWrapper$TypeProvider")); final Constructor mitpCtor = Reflections.getFirstCtor("org.springframework.core.SerializableTypeWrapper$MethodInvokeTypeProvider"); final Object mitp = mitpCtor.newInstance(typeProviderProxy, Object.class.getMethod("getClass", new Class[] {}), 0); Reflections.setFieldValue(mitp, "methodName", "newTransformer"); return mitp; }
81. ObjectCreator#createObject()
Project: jdonframework
File: ObjectCreator.java
File: ObjectCreator.java
/** * Instantaite an Object instance, requires a constractor with parameters * * @param classObject * , Class object representing the object type to be instantiated * @param params * an array including the required parameters to instantaite the * object * @return the instantaied Object * @exception java.lang.Exception * if instantiation failed */ public static Object createObject(Class classObject, Object[] params) throws Exception { Constructor[] constructors = classObject.getConstructors(); Object object = null; for (int counter = 0; counter < constructors.length; counter++) { try { object = constructors[counter].newInstance(params); } catch (Exception e) { if (e instanceof InvocationTargetException) ((InvocationTargetException) e).getTargetException().printStackTrace(); } } if (object == null) throw new InstantiationException(); return object; }
82. JdonConstructorInjectionComponentAdapter#getSortedMatchingConstructors()
Project: jdonframework
File: JdonConstructorInjectionComponentAdapter.java
File: JdonConstructorInjectionComponentAdapter.java
private List getSortedMatchingConstructors() { List matchingConstructors = new ArrayList(); Constructor[] allConstructors = getConstructors(); // filter out all constructors that will definately not match for (int i = 0; i < allConstructors.length; i++) { Constructor constructor = allConstructors[i]; if ((parameters == null || constructor.getParameterTypes().length == parameters.length) && (allowNonPublicClasses || (constructor.getModifiers() & Modifier.PUBLIC) != 0)) { matchingConstructors.add(constructor); } } // optimize list of constructors moving the longest at the beginning if (parameters == null) { Collections.sort(matchingConstructors, new Comparator() { public int compare(Object arg0, Object arg1) { return ((Constructor) arg1).getParameterTypes().length - ((Constructor) arg0).getParameterTypes().length; } }); } return matchingConstructors; }
83. ProxyArrays#genArrays()
Project: jdk7u-jdk
File: ProxyArrays.java
File: ProxyArrays.java
/** * Generate proxy arrays. */ Proxy[][] genArrays(int size, int narrays) throws Exception { Class proxyClass = Proxy.getProxyClass(DummyInterface.class.getClassLoader(), new Class[] { DummyInterface.class }); Constructor proxyCons = proxyClass.getConstructor(new Class[] { InvocationHandler.class }); Object[] consArgs = new Object[] { new DummyHandler() }; Proxy[][] arrays = new Proxy[narrays][size]; for (int i = 0; i < narrays; i++) { for (int j = 0; j < size; j++) { arrays[i][j] = (Proxy) proxyCons.newInstance(consArgs); } } return arrays; }
84. ProxyArrayCalls#genProxies()
Project: jdk7u-jdk
File: ProxyArrayCalls.java
File: ProxyArrayCalls.java
/** * Generate proxy object array of the given size. */ Proxy[] genProxies(int size) throws Exception { Class proxyClass = Proxy.getProxyClass(DummyInterface.class.getClassLoader(), new Class[] { DummyInterface.class }); Constructor proxyCons = proxyClass.getConstructor(new Class[] { InvocationHandler.class }); Object[] consArgs = new Object[] { new DummyHandler() }; Proxy[] proxies = new Proxy[size]; for (int i = 0; i < size; i++) proxies[i] = (Proxy) proxyCons.newInstance(consArgs); return proxies; }
85. ClassLoaderTest#main()
Project: jdk7u-jdk
File: ClassLoaderTest.java
File: ClassLoaderTest.java
public static void main(String[] args) throws Exception { Transform.init(); File file = new File(BASE); URL[] urls = new URL[1]; urls[0] = file.toURI().toURL(); URLClassLoader ucl = new URLClassLoader(urls); Class c = ucl.loadClass("MyTransform"); Constructor cons = c.getConstructor(); Object o = cons.newInstance(); // it again and catching an AlgorithmAlreadyRegisteredExc try { Transform.register(MyTransform.URI, "MyTransform"); throw new Exception("ClassLoaderTest failed"); } catch (AlgorithmAlreadyRegisteredException e) { } }
86. ClassLoader#run()
Project: jdk7u-jdk
File: ClassLoader.java
File: ClassLoader.java
public ClassLoader run() throws Exception { String cls = System.getProperty("java.system.class.loader"); if (cls == null) { return parent; } Constructor ctor = Class.forName(cls, true, parent).getDeclaredConstructor(new Class[] { ClassLoader.class }); ClassLoader sys = (ClassLoader) ctor.newInstance(new Object[] { parent }); Thread.currentThread().setContextClassLoader(sys); return sys; }
87. QueueByTypeFactory#createQueue()
Project: JCTools
File: QueueByTypeFactory.java
File: QueueByTypeFactory.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> Queue<T> createQueue(String queueType, final int queueCapacity) { try { int qType = Integer.valueOf(queueType); return createQueue(qType, queueCapacity); } catch (NumberFormatException e) { } Class qClass = queueClass(queueType); Constructor constructor; Exception ex; try { constructor = qClass.getConstructor(Integer.TYPE); return (Queue<T>) constructor.newInstance(queueCapacity); } catch (Exception e) { ex = e; } try { constructor = qClass.getConstructor(); return (Queue<T>) constructor.newInstance(); } catch (Exception e) { ex = e; } throw new IllegalArgumentException("Failed to construct queue:" + qClass.getName(), ex); }
88. MessagePassingQueueByTypeFactory#createQueue()
Project: JCTools
File: MessagePassingQueueByTypeFactory.java
File: MessagePassingQueueByTypeFactory.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> MessagePassingQueue<T> createQueue(String queueType, final int queueCapacity) { Class qClass = queueClass(queueType); Constructor constructor; Exception ex; try { constructor = qClass.getConstructor(Integer.TYPE); return (MessagePassingQueue<T>) constructor.newInstance(queueCapacity); } catch (Exception e) { ex = e; } try { constructor = qClass.getConstructor(); return (MessagePassingQueue<T>) constructor.newInstance(); } catch (Exception e) { ex = e; } throw new IllegalArgumentException("Failed to construct queue:" + qClass.getName(), ex); }
89. JavaArgumentsDefinition#createFrom()
Project: ioke
File: JavaArgumentsDefinition.java
File: JavaArgumentsDefinition.java
public static JavaArgumentsDefinition createFrom(Constructor[] m, boolean special) { sortByParameterOrdering(m); Class[][] params = new Class[m.length][]; int ix = 0; int min = -1; int max = -1; for (Constructor ms : m) { params[ix++] = ms.getParameterTypes(); int num = params[ix - 1].length; if (min == -1 || num < min) { min = num; } if (max == -1 || num > max) { max = num; } } return new JavaArgumentsDefinition(m, params, min, max, special); }
90. CachingConstructorInjectionComponentAdapter#getSortedMatchingConstructors()
Project: intellij-community
File: CachingConstructorInjectionComponentAdapter.java
File: CachingConstructorInjectionComponentAdapter.java
private List<Constructor> getSortedMatchingConstructors() { List<Constructor> matchingConstructors = new ArrayList<Constructor>(); // filter out all constructors that will definitely not match for (Constructor constructor : getConstructors()) { if ((parameters == null || constructor.getParameterTypes().length == parameters.length) && (allowNonPublicClasses || (constructor.getModifiers() & Modifier.PUBLIC) != 0)) { matchingConstructors.add(constructor); } } // optimize list of constructors moving the longest at the beginning if (parameters == null) { Collections.sort(matchingConstructors, new Comparator<Constructor>() { public int compare(Constructor arg0, Constructor arg1) { return arg1.getParameterTypes().length - arg0.getParameterTypes().length; } }); } return matchingConstructors; }
91. NotNullVerifyingInstrumenterTest#testUseParameterNames()
Project: intellij-community
File: NotNullVerifyingInstrumenterTest.java
File: NotNullVerifyingInstrumenterTest.java
public void testUseParameterNames() throws Exception { Class<?> testClass = prepareTest(true); Constructor constructor = testClass.getConstructor(Object.class, Object.class); verifyCallThrowsException("Argument for @NotNull parameter 'obj2' of UseParameterNames.<init> must not be null", null, constructor, null, null); Method staticMethod = testClass.getMethod("staticMethod", Object.class); verifyCallThrowsException("Argument for @NotNull parameter 'y' of UseParameterNames.staticMethod must not be null", null, staticMethod, (Object) null); Object instance = constructor.newInstance("", ""); Method instanceMethod = testClass.getMethod("instanceMethod", Object.class); verifyCallThrowsException("Argument for @NotNull parameter 'x' of UseParameterNames.instanceMethod must not be null", instance, instanceMethod, (Object) null); }
92. aClassLoader#run()
Project: intellij-community
File: aClassLoader.java
File: aClassLoader.java
public Object run() throws Exception { ClassLoader sys; Constructor ctor; Class c; Class cp[] = { ClassLoader.class }; Object params[] = { parent }; String cls = System.getProperty("java.system.class.loader"); if (cls == null) { return parent; } c = Class.forName(cls, true, parent); ctor = c.getDeclaredConstructor(cp); sys = (ClassLoader) ctor.newInstance(params); Thread.currentThread().setContextClassLoader(sys); return sys; }
93. ApiSurface#getExposedInvokables()
Project: incubator-beam
File: ApiSurface.java
File: ApiSurface.java
/** * Returns an {@link Invokable} for each public methods or constructors of a type. */ private Set<Invokable> getExposedInvokables(TypeToken<?> type) { Set<Invokable> invokables = Sets.newHashSet(); for (Constructor constructor : type.getRawType().getConstructors()) { if (0 != (constructor.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED))) { invokables.add(type.constructor(constructor)); } } for (Method method : type.getRawType().getMethods()) { if (0 != (method.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED))) { invokables.add(type.method(method)); } } return invokables; }
94. SnapshotUtilities#canExportScreenshotEps()
Project: igv
File: SnapshotUtilities.java
File: SnapshotUtilities.java
public static boolean canExportScreenshotEps() { Constructor constr = null; try { Class colorModeClass = RuntimeUtils.loadClassForName(EPSColorModeClassName, null); Class graphicsClass = RuntimeUtils.loadClassForName(EPSClassName, null); constr = graphicsClass.getConstructor(String.class, OutputStream.class, int.class, int.class, int.class, int.class, colorModeClass); } catch (Exception e) { } return constr != null; }
95. BindingTest#testToConstructorBindingsFailsOnRawTypes()
Project: guice
File: BindingTest.java
File: BindingTest.java
public void testToConstructorBindingsFailsOnRawTypes() throws NoSuchMethodException { final Constructor constructor = C.class.getConstructor(Stage.class, Object.class); try { Guice.createInjector(new AbstractModule() { protected void configure() { bind(Object.class).toConstructor(constructor); } }); fail(); } catch (CreationException expected) { assertContains(expected.getMessage(), "1) T cannot be used as a key; It is not fully specified.", "at " + C.class.getName() + ".<init>(BindingTest.java:", "2) T cannot be used as a key; It is not fully specified.", "at " + C.class.getName() + ".anotherT(BindingTest.java:"); } }
96. MethodRankHelper#getConstructorSuggestionString()
Project: groovy-core
File: MethodRankHelper.java
File: MethodRankHelper.java
/** * Returns a string detailing possible solutions to a missing constructor * if no good solutions can be found a empty string is returned. * * @param arguments the arguments passed to the constructor * @param type the class on which the constructor is invoked * @return a string with probable solutions to the exception */ public static String getConstructorSuggestionString(Class type, Object[] arguments) { Constructor[] sugg = rankConstructors(arguments, type.getConstructors()); if (sugg.length > 0) { StringBuilder sb = new StringBuilder(); sb.append("\nPossible solutions: "); for (int i = 0; i < sugg.length; i++) { if (i != 0) sb.append(", "); sb.append(type.getName()).append("("); sb.append(listParameterNames(sugg[i].getParameterTypes())); sb.append(")"); } return sb.toString(); } else { return ""; } }
97. CachedConstructor#invoke()
Project: groovy-core
File: CachedConstructor.java
File: CachedConstructor.java
public Object invoke(Object[] argumentArray) { Constructor constr = cachedConstructor; try { return constr.newInstance(argumentArray); } catch (InvocationTargetException e) { throw e.getCause() instanceof RuntimeException ? (RuntimeException) e.getCause() : new InvokerInvocationException(e); } catch (IllegalArgumentException e) { throw createExceptionText("failed to invoke constructor: ", constr, argumentArray, e, false); } catch (IllegalAccessException e) { throw createExceptionText("could not access constructor: ", constr, argumentArray, e, false); } catch (Exception e) { if (e instanceof RuntimeException) throw (RuntimeException) e; else throw createExceptionText("failed to invoke constructor: ", constr, argumentArray, e, true); } }
98. Inspector#getMethods()
Project: groovy-core
File: Inspector.java
File: Inspector.java
/** * Get info about usual Java instance and class Methods as well as Constructors. * * @return Array of StringArrays that can be indexed with the MEMBER_xxx_IDX constants */ public Object[] getMethods() { Method[] methods = getClassUnderInspection().getMethods(); Constructor[] ctors = getClassUnderInspection().getConstructors(); Object[] result = new Object[methods.length + ctors.length]; int resultIndex = 0; for (; resultIndex < methods.length; resultIndex++) { Method method = methods[resultIndex]; result[resultIndex] = methodInfo(method); } for (int i = 0; i < ctors.length; i++, resultIndex++) { Constructor ctor = ctors[i]; result[resultIndex] = methodInfo(ctor); } return result; }
99. MethodRankHelper#getConstructorSuggestionString()
Project: groovy
File: MethodRankHelper.java
File: MethodRankHelper.java
/** * Returns a string detailing possible solutions to a missing constructor * if no good solutions can be found a empty string is returned. * * @param arguments the arguments passed to the constructor * @param type the class on which the constructor is invoked * @return a string with probable solutions to the exception */ public static String getConstructorSuggestionString(Class type, Object[] arguments) { Constructor[] sugg = rankConstructors(arguments, type.getConstructors()); if (sugg.length > 0) { StringBuilder sb = new StringBuilder(); sb.append("\nPossible solutions: "); for (int i = 0; i < sugg.length; i++) { if (i != 0) sb.append(", "); sb.append(type.getName()).append("("); sb.append(listParameterNames(sugg[i].getParameterTypes())); sb.append(")"); } return sb.toString(); } else { return ""; } }
100. CachedConstructor#invoke()
Project: groovy
File: CachedConstructor.java
File: CachedConstructor.java
public Object invoke(Object[] argumentArray) { Constructor constr = cachedConstructor; try { return constr.newInstance(argumentArray); } catch (InvocationTargetException e) { throw e.getCause() instanceof RuntimeException ? (RuntimeException) e.getCause() : new InvokerInvocationException(e); } catch (IllegalArgumentException e) { throw createExceptionText("failed to invoke constructor: ", constr, argumentArray, e, false); } catch (IllegalAccessException e) { throw createExceptionText("could not access constructor: ", constr, argumentArray, e, false); } catch (Exception e) { if (e instanceof RuntimeException) throw (RuntimeException) e; else throw createExceptionText("failed to invoke constructor: ", constr, argumentArray, e, true); } }