private Object newInstance(Class type) { try { return type.newInstance(); } catch (Exception ex) { try { // Try a private constructor. Constructor constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (SecurityException ignored) { } catch (NoSuchMethodException ignored) { if (type.isArray()) throw new SerializationException( "Encountered JSON object when expected array of type: " + type.getName(), ex); else if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers())) throw new SerializationException( "Class cannot be created (non-static member class): " + type.getName(), ex); else throw new SerializationException( "Class cannot be created (missing no-arg constructor): " + type.getName(), ex); } catch (Exception privateConstructorException) { ex = privateConstructorException; } throw new SerializationException( "Error constructing instance of class: " + type.getName(), ex); } }
public static void setAllAccessible() { chatSerializer.setAccessible(true); titlePacketConstructor.setAccessible(true); titlePacketConstructorTimes.setAccessible(true); chatPacketConstructor.setAccessible(true); getHandle.setAccessible(true); playerConnection.setAccessible(true); sendPacket.setAccessible(true); }
/** * 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); }
@SuppressWarnings("rawtypes") @Override public void afterPropertiesSet() throws Exception { if (addresses == null || addresses.length == 0) { throw new IllegalArgumentException("addresses can not be null."); } if (bossExecutor == null) { acceptor = (HsfAcceptor) objectType.newInstance(); } else if (workerExecutor != null) { Constructor<?> ctor = objectType.getConstructor(Executor.class, Executor.class, Integer.class); ctor.setAccessible(true); acceptor = (HsfAcceptor) ctor.newInstance(bossExecutor, workerExecutor, workerCount); } else { Constructor<?> ctor = objectType.getConstructor(Executor.class, Integer.class); ctor.setAccessible(true); acceptor = (HsfAcceptor) ctor.newInstance(bossExecutor, workerCount); } if (eventExecutor != null) { acceptor.setEventExecutor(eventExecutor); } if (groupName != null) { acceptor.setGroupName(groupName); } if (options != null) { acceptor.setOptions(options); } if (handlers != null) { acceptor.setHandlers(handlers); } if (listeners != null) { acceptor.setListeners(listeners); } if (preDispatchInterceptors != null) { acceptor.setPreDispatchInterceptors( new LinkedList<PreDispatchInterceptor>(preDispatchInterceptors)); } if (services != null) { acceptor.setServices(services); } }
@SuppressWarnings({"unchecked", "rawtypes"}) private void registerEventHandlers_() { if (!Boolean.parseBoolean( Play.configuration.getProperty("morphia.autoRegisterEventHandler", "true"))) return; // -- register handlers from event handler class -- List<Class> classes = Play.classloader.getAssignableClasses(IMorphiaEventHandler.class); for (Class c : classes) { IMorphiaEventHandler h = null; try { Constructor cnst = c.getDeclaredConstructor(); cnst.setAccessible(true); h = (IMorphiaEventHandler) cnst.newInstance(); } catch (Exception e) { Logger.error(e, "Cannot init IMorphiaEventHandler from class: %s", c.getName()); continue; } Watch w = (Watch) c.getAnnotation(Watch.class); if (null != w) { Class[] ca = w.value(); for (Class modelClass : ca) { registerModelEventHandlers_(modelClass, h); } } } // -- register handlers from model class -- classes = Play.classloader.getAssignableClasses(Model.class); for (Class c : classes) { WatchBy wb = (WatchBy) c.getAnnotation(WatchBy.class); if (null == wb) continue; Class[] ca = wb.value(); for (Class handler : ca) { if ((IMorphiaEventHandler.class.isAssignableFrom(handler))) { IMorphiaEventHandler h = null; try { Constructor cnst = handler.getDeclaredConstructor(); cnst.setAccessible(true); h = (IMorphiaEventHandler) cnst.newInstance(); } catch (Exception e) { Logger.error(e, "Cannot init IMorphiaEventHandler from class: %s", c.getName()); continue; } registerModelEventHandlers_(c, h); } } } }
protected final JComponent buildPage(String className, PropertyValueModel subjectHolder) throws Exception { Class page = Class.forName(className); Constructor constructor = page.getDeclaredConstructor(new Class[] {PropertyValueModel.class}); constructor.setAccessible(true); return (JComponent) constructor.newInstance(new Object[] {subjectHolder}); }
/** * 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); } }
/** Calls the private constructor of the parser */ @SuppressWarnings("unused") private AndroidTargetParser _Constructor(String osJarPath) throws Exception { Constructor<AndroidTargetParser> constructor = AndroidTargetParser.class.getDeclaredConstructor(String.class); constructor.setAccessible(true); return constructor.newInstance(osJarPath); }
@BeforeClass public void initCronService() throws Exception { Constructor<CronService> constructor = CronService.class.getDeclaredConstructor(); constructor.setAccessible(true); cronService = constructor.newInstance(); cronService.init(CurrentThreadRunnableRunner.class); }
public static void create() throws Exception { ObjectType type = ObjectType.get(getControllerClass()); notFoundIfNull(type); Constructor<?> constructor = type.entityClass.getDeclaredConstructor(); constructor.setAccessible(true); Model object = (Model) constructor.newInstance(); Binder.bindBean(params.getRootParamNode(), "object", object); validation.valid(object); if (validation.hasErrors()) { renderArgs.put("error", play.i18n.Messages.get("crud.hasErrors")); try { render(request.controller.replace(".", "/") + "/blank.html", type, object); } catch (TemplateNotFoundException e) { render("CRUD/blank.html", type, object); } } object._save(); flash.success(play.i18n.Messages.get("crud.created", type.modelName)); if (params.get("_save") != null) { redirect(request.controller + ".list"); } if (params.get("_saveAndAddAnother") != null) { redirect(request.controller + ".blank"); } redirect(request.controller + ".show", object._key()); }
/** * 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(); }
@Implementation public AlertDialog create() { AlertDialog realDialog; try { Constructor<AlertDialog> c = AlertDialog.class.getDeclaredConstructor(Context.class); c.setAccessible(true); realDialog = c.newInstance((Context) null); } catch (Exception e) { throw new RuntimeException(e); } ShadowAlertDialog latestAlertDialog = shadowOf(realDialog); latestAlertDialog.context = context; latestAlertDialog.items = items; latestAlertDialog.setTitle(title); latestAlertDialog.message = message; latestAlertDialog.clickListener = clickListener; latestAlertDialog.setOnCancelListener(cancelListener); latestAlertDialog.isMultiItem = isMultiItem; latestAlertDialog.isSingleItem = isSingleItem; latestAlertDialog.checkedItemIndex = checkedItem; latestAlertDialog.multiChoiceClickListener = multiChoiceClickListener; latestAlertDialog.checkedItems = checkedItems; latestAlertDialog.setView(view); latestAlertDialog.positiveButton = createButton(realDialog, AlertDialog.BUTTON_POSITIVE, positiveText, positiveListener); latestAlertDialog.negativeButton = createButton(realDialog, AlertDialog.BUTTON_NEGATIVE, negativeText, negativeListener); latestAlertDialog.neutralButton = createButton(realDialog, AlertDialog.BUTTON_NEUTRAL, neutralText, neutralListener); latestAlertDialog.setCancelable(isCancelable); latestAlertDialog.customTitleView = customTitleView; return realDialog; }
protected static DeviceImpl importFromBEncodedMapStatic(DeviceManagerImpl manager, Map map) throws IOException { String impl = ImportExportUtils.importString(map, "_impl"); if (impl.startsWith(".")) { impl = MY_PACKAGE + impl; } try { Class<DeviceImpl> cla = (Class<DeviceImpl>) Class.forName(impl); Constructor<DeviceImpl> cons = cla.getDeclaredConstructor(DeviceManagerImpl.class, Map.class); cons.setAccessible(true); return (cons.newInstance(manager, map)); } catch (Throwable e) { Debug.out("Can't construct device for " + impl, e); throw (new IOException("Construction failed: " + Debug.getNestedExceptionMessage(e))); } }
/** * Accuracy test case for logInputArguments. * * @throws Exception to JUnit */ @SuppressWarnings("unchecked") @Test public void testLogInputArguments() throws Exception { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); Constructor privateCtor = BasicLog.class.getDeclaredConstructor(String.class, PrintStream.class); privateCtor.setAccessible(true); Log log = (Log) privateCtor.newInstance("name", new PrintStream(byteStream)); List<Long> list = new ArrayList<Long>(); list.add(1l); list.add(2l); Helper.logInputArguments( log, new String[] { "list", "user", "CopilotProfile", "null parameter", "CopilotProfileDTO", "CopilotProjectDTO", "CopilotPoolMember" }, new Object[] { list, "user", new CopilotProfile(), null, new CopilotProfileDTO(), new CopilotProjectDTO(), new CopilotPoolMember() }); String out = byteStream.toString(); assertTrue("Should contain 'Input arguments:'.", out.indexOf("Input arguments:") != -1); }
@Test public void private_constructor() throws Exception { Constructor constructor = TextUtils.class.getDeclaredConstructor(); assertThat(constructor.isAccessible()).isFalse(); constructor.setAccessible(true); constructor.newInstance(); }
/** Constructs an object with the given parameters and classtypes */ public static Object invokeConstructor(Class clazz, Object[] args, Class[] classTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor cs = getConstructorImpl(clazz, classTypes); cs.setAccessible(true); return cs.newInstance(args); }
private View instantiate(String name, Context context, AttributeSet attrs) { try { Constructor<? extends View> constructor = CONSTRUCTOR_MAP.get(name); if (constructor == null) { Class<? extends View> clazz = null; if (name.indexOf('.') != -1) { clazz = context.getClassLoader().loadClass(name).asSubclass(View.class); } else { for (String prefix : CLASS_PREFIX_LIST) { try { clazz = context.getClassLoader().loadClass(prefix + name).asSubclass(View.class); break; } catch (ClassNotFoundException e) { } } if (clazz == null) throw new ClassNotFoundException("couldn't find class: " + name); } constructor = clazz.getConstructor(CONSTRUCTOR_SIGNATURE); CONSTRUCTOR_MAP.put(name, constructor); } Object[] args = constructorArgs; args[0] = context; args[1] = attrs; constructor.setAccessible(true); View view = constructor.newInstance(args); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && view instanceof ViewStub) CompatibilityImpl.setLayoutInflater((ViewStub) view, inflater.cloneInContext(context)); return view; } catch (Exception e) { Logger.e(TAG, "couldn't instantiate class " + name, e); return null; } }
private <T> ObjectConstructor<T> newDefaultConstructor(Class<? super T> rawType) { try { final Constructor<? super T> constructor = rawType.getDeclaredConstructor(new Class[0]); if (!constructor.isAccessible()) { constructor.setAccessible(true); } new ObjectConstructor() { public T construct() { try { Object[] args = null; return (T) constructor.newInstance(args); } catch (InstantiationException e) { throw new RuntimeException("Failed to invoke " + constructor + " with no args", e); } catch (InvocationTargetException e) { throw new RuntimeException( "Failed to invoke " + constructor + " with no args", e.getTargetException()); } catch (IllegalAccessException e) { throw new AssertionError(e); } } }; } catch (NoSuchMethodException e) { } return null; }
protected CustomEventBanner internalCreate(String className) throws Exception { Class<? extends CustomEventBanner> bannerClass = Class.forName(className).asSubclass(CustomEventBanner.class); Constructor<?> bannerConstructor = bannerClass.getDeclaredConstructor((Class[]) null); bannerConstructor.setAccessible(true); return (CustomEventBanner) bannerConstructor.newInstance(); }
@Override public NeuralNetwork clone() { try { Constructor<?> c = Dl4jReflection.getEmptyConstructor(getClass()); c.setAccessible(true); NeuralNetwork ret = (NeuralNetwork) c.newInstance(); ret.setMomentumAfter(momentumAfter); ret.setResetAdaGradIterations(resetAdaGradIterations); ret.setHbiasAdaGrad(hBiasAdaGrad); ret.setVBiasAdaGrad(vBiasAdaGrad); ret.sethBias(hBias.dup()); ret.setvBias(vBias.dup()); ret.setnHidden(getnHidden()); ret.setnVisible(getnVisible()); ret.setW(W.dup()); ret.setL2(l2); ret.setMomentum(momentum); ret.setRenderEpochs(getRenderIterations()); ret.setSparsity(sparsity); ret.setRng(getRng()); ret.setDist(getDist()); ret.setAdaGrad(wAdaGrad); ret.setLossFunction(lossFunction); ret.setConstrainGradientToUnitNorm(constrainGradientToUnitNorm); ret.setOptimizationAlgorithm(optimizationAlgo); return ret; } catch (Exception e) { throw new RuntimeException(e); } }
/** * 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[] {}); }
@Test public void giveMeCoverageForMyPrivateConstructor() throws Exception { // reduces only some noise in coverage report final Constructor<UrlUtil> constructor = UrlUtil.class.getDeclaredConstructor(); constructor.setAccessible(true); constructor.newInstance(); }
/** * Create a new instance by finding a constructor that matches the argumentTypes signature using * the arguments for instantiation. * * @param className Full classname of class to create * @param argumentTypes The constructor argument types * @param arguments The constructor arguments * @return a new instance * @throws IllegalArgumentException if className, argumentTypes, or arguments are null * @throws RuntimeException if any exceptions during creation * @author <a href="mailto:[email protected]">Aslak Knutsen</a> * @author <a href="mailto:[email protected]">ALR</a> */ static <T> T newInstance( final Class<T> implClass, final Class<?>[] argumentTypes, final Object[] arguments) { if (implClass == null) { throw new IllegalArgumentException("ImplClass must be specified"); } if (argumentTypes == null) { throw new IllegalArgumentException( "ArgumentTypes must be specified. Use empty array if no arguments"); } if (arguments == null) { throw new IllegalArgumentException( "Arguments must be specified. Use empty array if no arguments"); } final T obj; try { Constructor<T> constructor = getConstructor(implClass, argumentTypes); if (!constructor.isAccessible()) { constructor.setAccessible(true); } obj = constructor.newInstance(arguments); } catch (Exception e) { throw new RuntimeException("Could not create new instance of " + implClass, e); } return obj; }
/** Invokes a given method via {@link Method#invoke(Object, Object...)}. */ default Object invoke(ResolvedJavaMethod method, Object receiver, Object... args) { try { JavaType[] parameterTypes = method.toParameterTypes(); Class<?>[] parameterClasses = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterClasses.length; ++i) { JavaType type = parameterTypes[i]; if (type.getJavaKind() != JavaKind.Object) { parameterClasses[i] = type.getJavaKind().toJavaClass(); } else { parameterClasses[i] = resolveClassForSnippet(parameterTypes[i]); } } Class<?> c = resolveClassForSnippet(method.getDeclaringClass()); if (method.isConstructor()) { Constructor<?> javaConstructor = c.getDeclaredConstructor(parameterClasses); javaConstructor.setAccessible(true); return javaConstructor.newInstance(args); } else { Method javaMethod = c.getDeclaredMethod(method.getName(), parameterClasses); javaMethod.setAccessible(true); return javaMethod.invoke(receiver, args); } } catch (IllegalAccessException | InstantiationException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException ex) { throw new IllegalArgumentException(ex); } }
private static <T> T getInstanceFromNonDefaultConstructor(Class<T> targetClass) { Constructor<?>[] constructors = targetClass.getDeclaredConstructors(); constructors = DatabaseFileLookupTest.orderByParamCount(constructors); for (Constructor<?> constructor : constructors) { constructor.setAccessible(true); Class<?>[] parameterTypes = constructor.getParameterTypes(); try { /** Trying to invoke constructor with <code>null</code> values. */ @SuppressWarnings("unchecked") T instance = (T) constructor.newInstance(new Object[parameterTypes.length]); return instance; } catch (Exception ignored) { } /** Creating proper instances for the parameter types. */ Object[] arguments = DatabaseFileLookupTest.createArguments(parameterTypes, targetClass); if (arguments == null) { continue; } try { @SuppressWarnings("unchecked") T instance = (T) constructor.newInstance(arguments); return instance; } catch (Exception ignored) { } } return null; }
private void prepareSuite() { Class<?> benchmarkClass; try { benchmarkClass = getClassByName(suiteClassName); } catch (ExceptionInInitializerError e) { throw new ExceptionFromUserCodeException(e.getCause()); } catch (ClassNotFoundException ignored) { throw new NoSuchClassException(suiteClassName); } Object s; try { Constructor<?> constructor = benchmarkClass.getDeclaredConstructor(); constructor.setAccessible(true); s = constructor.newInstance(); } catch (InstantiationException ignore) { throw new AbstractBenchmarkException(benchmarkClass); } catch (NoSuchMethodException ignore) { throw new NoParameterlessConstructorException(benchmarkClass); } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); // shouldn't happen since we setAccessible(true) } catch (InvocationTargetException e) { throw new ExceptionFromUserCodeException(e.getCause()); } if (s instanceof Benchmark) { this.suite = (Benchmark) s; } else { throw new DoesntImplementBenchmarkException(benchmarkClass); } }
@SuppressWarnings("unused") private static Object _invoke( MethodHandler methodHandler, Class<? extends ClusterInvokeAcceptor> clusterInvokeAcceptorClass, Map<String, Serializable> context) throws Exception { if (clusterInvokeAcceptorClass != null) { Constructor<? extends ClusterInvokeAcceptor> constructor = clusterInvokeAcceptorClass.getDeclaredConstructor(); if (!constructor.isAccessible()) { constructor.setAccessible(true); } ClusterInvokeAcceptor clusterInvokeAcceptor = constructor.newInstance(); if (!clusterInvokeAcceptor.accept(context)) { return null; } } _populateThreadLocalsFromContext(context); return methodHandler.invoke(); }
@BeforeClass public static void setUpClass() throws Exception { PortalUtil portalUtil = new PortalUtil(); portalUtil.setPortal(new PortalImpl()); PortalUUIDUtil portalUUIDUtil = new PortalUUIDUtil(); portalUUIDUtil.setPortalUUID(new PortalUUIDImpl()); Field field = ReflectionUtil.getDeclaredField(LockLocalServiceUtil.class, "_service"); LockLocalService lockLocalService = new MockLockLocalService(); field.set(null, lockLocalService); field = ClusterableContextThreadLocal.class.getDeclaredField("_contextThreadLocal"); field.setAccessible(true); _threadLocalContext = (ThreadLocal<HashMap<String, Serializable>>) field.get(null); Method method = ClusterSchedulerEngine.class.getDeclaredMethod("delete", String.class); Clusterable clusterable = method.getAnnotation(Clusterable.class); Class<? extends ClusterInvokeAcceptor> clusterInvokeAcceptorClass = clusterable.acceptor(); Constructor<? extends ClusterInvokeAcceptor> constructor = clusterInvokeAcceptorClass.getDeclaredConstructor(); constructor.setAccessible(true); _clusterInvokeAcceptor = constructor.newInstance(); }
public static void main(String[] args) throws Exception { System.out.println("Well, you think your EnumSingleton is really a singleton"); System.out.println( "The id of the INSTANCE object is " + System.identityHashCode(EnumSingleton.INSTANCE)); System.out.println("I will create another instance using reflection"); Constructor<EnumSingleton> privateConstructor = EnumSingleton.class.getDeclaredConstructor(String.class, int.class); privateConstructor.setAccessible(true); try { privateConstructor.newInstance(); } catch (IllegalArgumentException e) { System.out.println( "D'oh! An exception prevented me from creating a new instance: " + e.getMessage()); } System.out.println("Hmm, I will try one more option - Serialisation"); EnumSingleton clone = SerializationUtils.clone(EnumSingleton.INSTANCE); System.out.println( "D'oh! Even serialization did not work. id = " + System.identityHashCode(clone)); System.out.println("I give up"); }
public MySocketImplFactory() throws ClassNotFoundException, SecurityException, NoSuchMethodException { super(); Class<?> c = Class.forName("java.net.PlainSocketImpl"); constructor = c.getDeclaredConstructor(); constructor.setAccessible(true); accept = c.getDeclaredMethod("accept", SocketImpl.class); accept.setAccessible(true); bind = c.getDeclaredMethod("bind", InetAddress.class, Integer.TYPE); bind.setAccessible(true); available = c.getDeclaredMethod("available"); available.setAccessible(true); create = c.getDeclaredMethod("create", Boolean.TYPE); create.setAccessible(true); connect1 = c.getDeclaredMethod("connect", InetAddress.class, Integer.TYPE); connect1.setAccessible(true); connect2 = c.getDeclaredMethod("connect", SocketAddress.class, Integer.TYPE); connect2.setAccessible(true); connect3 = c.getDeclaredMethod("connect", String.class, Integer.TYPE); connect3.setAccessible(true); getInputStream = c.getDeclaredMethod("getInputStream"); getInputStream.setAccessible(true); getOutputStream = c.getDeclaredMethod("getOutputStream"); getOutputStream.setAccessible(true); close = c.getDeclaredMethod("close"); close.setAccessible(true); sendUrgentData = c.getDeclaredMethod("sendUrgentData", Integer.TYPE); sendUrgentData.setAccessible(true); listen = c.getDeclaredMethod("listen", Integer.TYPE); listen.setAccessible(true); }