/** * Retrieves a new HsqlSocketFactory whose class * is determined by the implClass argument. The basic contract here * is that implementations constructed by this method should return * true upon calling isSecure() iff they actually create secure sockets. * There is no way to guarantee this directly here, so it is simply * trusted that an implementation is secure if it returns true * for calls to isSecure(); * * @return a new secure socket factory * @param implClass the fully qaulified name of the desired * class to construct * @throws Exception if a new secure socket factory cannot * be constructed */ private static HsqlSocketFactory newFactory(String implClass) throws Exception { Class clazz; Constructor ctor; Class[] ctorParm; Object[] ctorArg; Object factory; clazz = Class.forName(implClass); ctorParm = new Class[0]; // protected constructor ctor = clazz.getDeclaredConstructor(ctorParm); ctorArg = new Object[0]; try { factory = ctor.newInstance(ctorArg); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); throw (t instanceof Exception) ? ((Exception) t) : new RuntimeException( t.toString()); } return (HsqlSocketFactory) factory; }
public NMethod compile(int level) { String directive = "[{ match: \"" + executable.getDeclaringClass().getName().replace('.', '/') + "." + (executable instanceof Constructor ? "<init>" : executable.getName()) + "\", " + "BackgroundCompilation: false }]"; if (WB.addCompilerDirective(directive) != 1) { throw new Error("Failed to add compiler directive: " + directive); } boolean enqueued = WB.enqueueMethodForCompilation(executable, level, bci); if (!enqueued) { throw new Error(String.format( "%s can't be enqueued for %scompilation on level %d", executable, bci >= 0 ? "osr-" : "", level)); } Utils.waitForCondition(() -> WB.isMethodCompiled(executable, isOsr)); return NMethod.get(executable, isOsr); }
/** * Creates a new JSON ORM by using the class. * @param clazz The class of the container that will be worked with. * @throws IllegalArgumentException If the provided class has no empty constructor. * @throws IllegalStateException If the provided class could not be instantiated. */ JSONORM(Class<T> clazz) throws IllegalArgumentException { Constructor<?> constructor = null; for(Constructor<?> tConstructor : clazz.getDeclaredConstructors()) { if(tConstructor.getParameterCount() == 0) { constructor = tConstructor; } } if(constructor == null) { throw new IllegalArgumentException("Provided class " + clazz + " has no empty constructor"); } constructor.setAccessible(true); try { //noinspection unchecked container = (T) constructor.newInstance(); } catch(InvocationTargetException | InstantiationException | IllegalAccessException exception) { throw new IllegalStateException("An internal error occurred, could not instantiate " + clazz); } }
public static ICrypt get(String name, String password) { String className = crypts.get(name); if (className == null) { return null; } try { Class<?> clazz = Class.forName(className); Constructor<?> constructor = clazz.getConstructor(String.class, String.class); return (ICrypt) constructor.newInstance(name, password); } catch (Exception e) { logger.error("get crypt error", e); } return null; }
private ClientCnxnSocket getClientCnxnSocket() throws IOException { String clientCnxnSocketName = getClientConfig().getProperty( ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET); if (clientCnxnSocketName == null) { clientCnxnSocketName = ClientCnxnSocketNIO.class.getName(); } try { Constructor<?> clientCxnConstructor = Class.forName(clientCnxnSocketName).getDeclaredConstructor(ZKClientConfig.class); ClientCnxnSocket clientCxnSocket = (ClientCnxnSocket) clientCxnConstructor.newInstance(getClientConfig()); return clientCxnSocket; } catch (Exception e) { IOException ioe = new IOException("Couldn't instantiate " + clientCnxnSocketName); ioe.initCause(e); throw ioe; } }
/** * Sort the given constructors, preferring public constructors and "greedy" ones with * a maximum number of arguments. The result will contain public constructors first, * with decreasing number of arguments, then non-public constructors, again with * decreasing number of arguments. * @param constructors the constructor array to sort */ public static void sortConstructors(Constructor<?>[] constructors) { Arrays.sort(constructors, new Comparator<Constructor<?>>() { @Override public int compare(Constructor<?> c1, Constructor<?> c2) { boolean p1 = Modifier.isPublic(c1.getModifiers()); boolean p2 = Modifier.isPublic(c2.getModifiers()); if (p1 != p2) { return (p1 ? -1 : 1); } int c1pl = c1.getParameterTypes().length; int c2pl = c2.getParameterTypes().length; return (new Integer(c1pl)).compareTo(c2pl) * -1; } }); }
@Test @Points("100.1") public void test7() { Constructor densityKonstruktori = ReflectionUtils.requireConstructor(clazz, double.class); Object inst = null; try { inst = ReflectionUtils.invokeConstructor(densityKonstruktori, 1.0); } catch (Throwable ex) { fail("Ensure that class " + tahtitaivasLuokka + " has constructor public " + tahtitaivasLuokka + "(double density)."); } int tahdet = 0; Method m = ReflectionUtils.requireMethod(clazz, printLineMetodi); try { ReflectionUtils.invokeMethod(void.class, m, inst); String out = stdio.getSysOut(); if (out == null || out.isEmpty()) { fail("Ensure that the method " + printLineMetodi + " prints something."); } } catch (Throwable t) { fail("Ensure that class " + tahtitaivasLuokka + " has method public void " + printLineMetodi + "() " + "\nCall to the method should print something"); } }
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; }
@Override public EntryHolder onCreateViewHolder(ViewGroup viewGroup, int type) { View view = LayoutInflater.from(viewGroup.getContext()) .inflate(sKnownViewHolderLayouts.get(type), viewGroup, false); try { try { return sKnownViewHolders.get(type).getDeclaredConstructor(View.class).newInstance(view); } catch (NoSuchMethodException e2) { for (Constructor constructor : sKnownViewHolders.get(type).getDeclaredConstructors()) { Class[] p = constructor.getParameterTypes(); if (p.length == 2 && p[0].equals(View.class) && EntryRecyclerViewAdapter.class.isAssignableFrom(p[1])) return (EntryHolder) constructor.newInstance(view, this); } throw new NoSuchMethodException(); } } catch (Exception e) { throw new RuntimeException(e); } }
/** * Create an object for the given class and initialize it from conf. * @param theClass class of which an object is created * @param conf Configuration * @return a new object */ @SuppressWarnings("unchecked") static <T> T newInstance(Class<T> theClass, URI uri, Configuration conf) { T result; try { Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass); if (meth == null) { meth = theClass.getDeclaredConstructor(URI_CONFIG_ARGS); meth.setAccessible(true); CONSTRUCTOR_CACHE.put(theClass, meth); } result = meth.newInstance(uri, conf); } catch (Exception e) { throw new RuntimeException(e); } return result; }
/** * 利用反射构建DataBase对象 * @param connInfo * @return DataBase */ public static <T extends Enum<T> & IDataSource> DataBase newInstanceDataBase(ConnectionInfo connInfo) { try { Constructor<?> dataBaseConstr = connInfo.getIDataSource().getDataBase().getDeclaredConstructor(ConnectionInfo.class); DataBase dataBase= (DataBase) dataBaseConstr.newInstance(connInfo); return dataBase; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); DBCException.logException(DBCException.E_newInstanceDataBase, e); return null; } }
/** * Returns accessible version of the given constructor. * @param <T> the type of the constructor * @param ctor prototype constructor object. * @return <code>null</code> if accessible constructor can not be found. * @see java.lang.SecurityManager */ public static <T> Constructor<T> getAccessibleConstructor(final Constructor<T> ctor) { // Make sure we have a method to check if (ctor == null) { return (null); } // If the requested method is not public we cannot call it if (!Modifier.isPublic(ctor.getModifiers())) { return (null); } // If the declaring class is public, we are done final Class<T> clazz = ctor.getDeclaringClass(); if (Modifier.isPublic(clazz.getModifiers())) { return (ctor); } // what else can we do? return null; }
/** * Create a specific instance of AppleImage. This has been coded * using Reflection to ease native compilation for the most part. */ public static AppleImage create(int width, int height) { String[] classes = { "ImageIoImage", "SunJpegImage", "SwtImage" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ Class[] constructorArgClasses = new Class[] { int.class, int.class }; Object[] constructorArgs = new Object[] { new Integer(width), new Integer(height) }; for (int i=0; i<classes.length; i++) { try { Class appleImageClass = Class.forName( "com.webcodepro.applecommander.storage.filters.imagehandlers." //$NON-NLS-1$ + classes[i]); Constructor constructor = appleImageClass.getConstructor(constructorArgClasses); AppleImage appleImage = (AppleImage) constructor.newInstance(constructorArgs); return appleImage; } catch (Exception ignored) { // There are multiple exceptions that can be thrown here. // For the most part, this is expected and simply means that // the image handler is not available on the platform. } } return null; }
/** * Creates a new dummy entity of the required type. Required non null foreign keys will be taken from the {@link #getDummy(AbstractRedG, Class)} method * and will be created if necessary as well. If the creation fails for some reason, a {@link DummyCreationException} will be thrown. * * @param redG The redG instance * @param dummyClass The class specifying the wanted entity type * @param <T> The wanted entity type * @return A new dummy entity of the required type. It has already been added to the redG object and can be used immediately. * @throws DummyCreationException If no fitting constructor is found or instantiation fails */ private <T extends RedGEntity> T createNewDummy(AbstractRedG redG, Class<T> dummyClass) { Constructor constructor = Arrays.stream(dummyClass.getDeclaredConstructors()) .filter(this::isDummyRedGEntityConstructor) .findFirst().orElseThrow(() -> new DummyCreationException("Could not find a fitting constructor")); Object[] parameter = new Object[constructor.getParameterCount()]; parameter[0] = redG; for (int i = 1; i < constructor.getParameterCount(); i++) { parameter[i] = getDummy(redG, constructor.getParameterTypes()[i]); } try { constructor.setAccessible(true); T obj = dummyClass.cast(constructor.newInstance(parameter)); redG.addEntity(obj); return obj; } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new DummyCreationException("Instantiation of the dummy failed", e); } }
/** * * 通用实体转换方法,将JPA返回的数组转化成对应的实体集合,这里通过泛型和反射实现 * * @param <T> * * @param list * * @param clazz 需要转化后的类型 * * @return * * @throws Exception */ public static <T> List<T> castEntity(List<Object[]> list, Class<T> clazz) { List<T> returnList = new ArrayList<T>(); if(list != null && !list.isEmpty()) { Object[] co = list.get(0); Class[] c2 = new Class[co.length]; try { //确定构造方法 for (int i = 0; i < co.length; i++) { c2[i] = co[i].getClass(); } for (Object[] o : list) { Constructor<T> constructor = clazz.getConstructor(c2); returnList.add(constructor.newInstance(o)); } } catch (Exception e) { logger.error("mapper error", e); } } return returnList; }
public static Constructor<?> getConstructor(Class<?> clazz, Class<?>... params) { if (!loadedConstructors.containsKey(clazz)) { loadedConstructors.put(clazz, new HashMap<>()); } Map<Class<?>[], Constructor<?>> clazzConstructors = loadedConstructors.get(clazz); if (clazzConstructors.containsKey(params)) { clazzConstructors.get(params); } Constructor<?> constructor = null; try { constructor = clazz.getConstructor(params); constructor.setAccessible(true); } catch (NoSuchMethodException e) { e.printStackTrace(); } clazzConstructors.put(params, constructor); loadedConstructors.put(clazz, clazzConstructors); return constructor; }
private BoltCommandHandlerProvider buildProvider() throws Exception { /*Set<Class<?>> classes = AnnotationScanner.scan("com.creditease.dbus", BoltCmdHandlerProvider.class, (clazz, annotation) -> { BoltCmdHandlerProvider ca = clazz.getAnnotation(BoltCmdHandlerProvider.class); return ca.type() == BoltType.HEARTBEAT_BOLT; }); if (classes.size() <= 0) throw new ProviderNotFoundException(); if (classes.size() > 1) { String providers = ""; for (Class<?> clazz : classes) { providers += clazz.getName() + " "; } throw new RuntimeException("too many providers found: " + providers); }*/ DbusDatasourceType type = GlobalCache.getDatasourceType(); String name; if(type == DbusDatasourceType.ORACLE) { name = "com.creditease.dbus.stream.oracle.appender.bolt.processor.provider.HeartbeatCmdHandlerProvider"; } else if(type == DbusDatasourceType.MYSQL) { name = "com.creditease.dbus.stream.mysql.appender.bolt.processor.provider.HeartbeatCmdHandlerProvider"; } else { throw new IllegalArgumentException("Illegal argument [" + type.toString() + "] for building BoltCommandHandler map!"); } Class<?> clazz = Class.forName(name); Constructor<?> constructor = clazz.getConstructor(HeartbeatHandlerListener.class); return (BoltCommandHandlerProvider) constructor.newInstance(this); }
public static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType) throws NoSuchMethodException { Constructor<?> targetConstructor; try { targetConstructor = clazz.getConstructor(new Class<?>[] {paramType}); } catch (NoSuchMethodException e) { targetConstructor = null; Constructor<?>[] constructors = clazz.getConstructors(); for (Constructor<?> constructor : constructors) { if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0].isAssignableFrom(paramType)) { targetConstructor = constructor; break; } } if (targetConstructor == null) { throw e; } } return targetConstructor; }
/** Check that we are not loading classes hungrily. * DataLoader(String) is prefered to avoid loading of DataObject classes. */ public void testDataLoaders() throws Exception { Enumeration<DataLoader> loaders = DataLoaderPool.getDefault().allLoaders(); while (loaders.hasMoreElements()) { DataLoader ldr = loaders.nextElement(); if ("org.netbeans.modules.cnd.loaders.CCDataLoader".equals(ldr.getClass().getName())) { // #97612 continue; } try { // XXX not enough better is to test that all ctors only call super(String) Constructor ctor = ldr.getClass().getDeclaredConstructor(Class.class); assertNull(ldr.getClass().getName()+".<init>(String) is better are usualy enough", ctor); } catch (NoSuchMethodException ex) { // expected path - OK } } }
public static HttpClient buildClient(BuilderParams builderParams) { try { String httpClientClassName = System.getProperty(HTTP_CLIENT_IMPL_KEY); if (StringUtils.isEmpty(httpClientClassName)) { httpClientClassName = DEFAULT_HTTP_CLIENT; } Class httpClientClass = Class.forName(httpClientClassName); if (!HttpClient.class.isAssignableFrom(httpClientClass)) { throw new IllegalStateException(String.format("%s is not assignable from com.alibaba.cloudapi.sdk.core.HttpClient", httpClientClassName)); } Constructor<? extends HttpClient> constructor = httpClientClass.getConstructor(BuilderParams.class); return constructor.newInstance(builderParams); } catch (Exception e) { throw new SdkClientException("HttpClientFactory buildClient failed", e); } }
public final static MessageStore build(MessageStorePluginContext context, MessageStore messageStore) throws IOException { String plugin = context.getBrokerConfig().getMessageStorePlugIn(); if (plugin != null && plugin.trim().length() != 0) { String[] pluginClasses = plugin.split(","); for (int i = pluginClasses.length - 1; i >= 0; --i) { String pluginClass = pluginClasses[i]; try { @SuppressWarnings("unchecked") Class<AbstractPluginMessageStore> clazz = (Class<AbstractPluginMessageStore>) Class.forName(pluginClass); Constructor<AbstractPluginMessageStore> construct = clazz.getConstructor(MessageStorePluginContext.class, MessageStore.class); messageStore = construct.newInstance(context, messageStore); } catch (Throwable e) { throw new RuntimeException(String.format( "Initialize plugin's class %s not found!", pluginClass), e); } } } return messageStore; }
public SignatureType(Executable method) { super(MethodDescriptor.Separator.NONE); // Get parameters Class<?>[] types = method.getParameterTypes(); String[] parameterTypes = new String[types.length]; for (int i = 0; i < types.length; i++) { parameterTypes[i] = Utils.toJVMTypeSignature(types[i]); } // Get return value String returnType; if (method instanceof Method) { returnType = Utils.toJVMTypeSignature(((Method) method) .getReturnType()); } else if (method instanceof Constructor) { // Constructor returns void in VM returnType = Utils.toJVMTypeSignature(void.class); } else { throw new Error(String.format("TESTBUG: wrong type of executable " + "%s of class %s", method, method.getClass())); } // Create signature setElement("(" + String.join("", parameterTypes)+ ")" + returnType); regexp = element; setPattern(MethodDescriptor.PatternType.EXACT); separator = MethodDescriptor.Separator.NONE; }
private void newInstanceFromConstructor(Class<?> proxyClass) throws Exception { // expect newInstance to succeed if it's in the same runtime package boolean isSamePackage = proxyClass.getName().lastIndexOf('.') == -1; try { Constructor cons = proxyClass.getConstructor(InvocationHandler.class); cons.newInstance(newInvocationHandler()); if (!isSamePackage) { throw new RuntimeException("ERROR: Constructor.newInstance should not succeed"); } } catch (IllegalAccessException e) { if (isSamePackage) { throw e; } } }
private void run() { byte[] bytecode = TestOSRWithNonEmptyStack.generateTestClass(); try { Class klass = defineClass(TestOSRWithNonEmptyStack.CLASS_NAME, bytecode, 0, bytecode.length); Constructor ctor = klass.getConstructor(); Method method = klass.getDeclaredMethod( TestOSRWithNonEmptyStack.METHOD_NAME); Object testCase = ctor.newInstance(); method.invoke(testCase); } catch (Exception e) { throw new RuntimeException( "Test bug: generated class should be valid.", e); } }
/** * Why must I do these? * Resource has mTypedArrayPool field, which just like Message Poll to reduce gc * MiuiResource change TypedArray to MiuiTypedArray, but it get string block from offset instead of assetManager */ private static void clearPreloadTypedArrayIssue(Resources resources) { // Perform this trick not only in Miui system since we can't predict if any other // manufacturer would do the same modification to Android. // if (!isMiuiSystem) { // return; // } Log.w(TAG, "try to clear typedArray cache!"); // Clear typedArray cache. try { Field typedArrayPoolField = ShareReflectUtil.findField(Resources.class, "mTypedArrayPool"); final Object origTypedArrayPool = typedArrayPoolField.get(resources); Field poolField = ShareReflectUtil.findField(origTypedArrayPool, "mPool"); final Constructor<?> typedArrayConstructor = origTypedArrayPool.getClass().getConstructor(int.class); typedArrayConstructor.setAccessible(true); final int poolSize = ((Object[]) poolField.get(origTypedArrayPool)).length; final Object newTypedArrayPool = typedArrayConstructor.newInstance(poolSize); typedArrayPoolField.set(resources, newTypedArrayPool); } catch (Throwable ignored) { Log.e(TAG, "clearPreloadTypedArrayIssue failed, ignore error: " + ignored); } }
private void addMethodProxy(Class<?> hookType) { try { Constructor<?> constructor = hookType.getDeclaredConstructors()[0]; if (!constructor.isAccessible()) { constructor.setAccessible(true); } MethodProxy methodProxy; if (constructor.getParameterTypes().length == 0) { methodProxy = (MethodProxy) constructor.newInstance(); } else { methodProxy = (MethodProxy) constructor.newInstance(this); } mInvocationStub.addMethodProxy(methodProxy); } catch (Throwable e) { throw new RuntimeException("Unable to instance Hook : " + hookType + " : " + e.getMessage()); } }
@Override public Object createStatement(Object proxy, Method method, Object[] args, Object statement, long time) { try { Object result; String name = method.getName(); String sql = null; Constructor<?> constructor; if (compare(CREATE_STATEMENT, name)) { constructor = getConstructor(CREATE_STATEMENT_IDX, Statement.class); } else if (compare(PREPARE_STATEMENT, name)) { sql = (String) args[0]; constructor = getConstructor(PREPARE_STATEMENT_IDX, PreparedStatement.class); } else if (compare(PREPARE_CALL, name)) { sql = (String) args[0]; constructor = getConstructor(PREPARE_CALL_IDX, CallableStatement.class); } else { return statement; } result = constructor.newInstance(new StatementProxy(statement, sql)); return result; } catch (Exception x) { logger.warn("Unable to create statement proxy for tracing.", x); } return statement; }
private UiObject2 doFindObject(Object selector, AccessibilityNodeInfo node) throws Exception { Class uiObject2 = Class.forName("android.support.test.uiautomator.UiObject2"); Constructor cons = uiObject2.getDeclaredConstructors()[0]; cons.setAccessible(true); Object[] constructorParams = {uiDevice, selector, node}; final long timeoutMillis = 1000; long end = SystemClock.uptimeMillis() + timeoutMillis; while (true) { UiObject2 object2 = (UiObject2) cons.newInstance(constructorParams); if (object2 != null) { return object2; } long remainingMillis = end - SystemClock.uptimeMillis(); if (remainingMillis < 0) { return null; } SystemClock.sleep(Math.min(200, remainingMillis)); } }
/** * Create a new {@link com.yammer.metrics.core.Histogram} instance. These constructors are * not public in 2.2.0, so we use reflection to find them. */ public static Histogram newHistogram(Sample sample) { try { Constructor<?> ctor = Histogram.class.getDeclaredConstructor(Sample.class); ctor.setAccessible(true); return (Histogram) ctor.newInstance(sample); } catch (Exception e) { throw new RuntimeException(e); } }
void addRecipe() { Class<DamageableShapedOreRecipe> recipeClass = JEICompatRegistry.getShapedCraftingRecipeClass(recipeList); Constructor<DamageableShapedOreRecipe> constructor = ReflectionHelper.getConstructor(recipeClass, ResourceLocation.class, int[].class, ItemStack.class, Object[].class); int[] damageAmounts = createDamageAmounts(getRecipeWidth(), getRecipeHeight(), shape, damage); DamageableShapedOreRecipe recipe = ReflectionHelper.newInstance(constructor, null, damageAmounts, result.getItemStack(), getInputForRecipe()); if (recipe != null) { recipe.setMirrored(mirrored); CraftingManagerCS4.addRecipe(recipeList, recipe); } }
@Test(expected = UnsupportedOperationException.class) public void testConstructorThrowsException() throws Throwable { Constructor<?> constructor = MockSingleModelWriter.class.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { constructor.newInstance(); } catch (InvocationTargetException ite) { throw ite.getTargetException(); } }
private static <T extends Member & AnnotatedElement> String getExpectedNameOf(T member, String name) { String base = member.getDeclaringClass().getName() + "." + name; if (member instanceof Method) { return base + expectedParametersOf(((Method) member).getParameterTypes()); } if (member instanceof Constructor<?>) { return base + expectedParametersOf(((Constructor<?>) member).getParameterTypes()); } return base; }
public static TProcessor buildProcessor(Class<?> svcInterface, Object service) throws Exception { Class<TProcessor> processorClass = (Class<TProcessor>) getThriftServiceInnerClassOrNull(svcInterface.getEnclosingClass(), PROCESSOR_NAME, false); if (processorClass == null) { throw new ThriftRuntimeException("the processor is null"); } Constructor<TProcessor> constructor = ClassUtils.getConstructorIfAvailable(processorClass, svcInterface); if (constructor == null) { throw new ThriftRuntimeException("the processor constructor is null"); } return constructor.newInstance(service); }
/** * Returns an InterfaceAddress instance with its fields set the the values * specificed. */ static InterfaceAddress createInterfaceAddress( InetAddress address, InetAddress broadcast, short prefixlength) { try { Class<InterfaceAddress> IAClass = InterfaceAddress.class; InterfaceAddress ia; Constructor<InterfaceAddress> ctr = IAClass.getDeclaredConstructor(); ctr.setAccessible(true); Field addressField = IAClass.getDeclaredField("address"); addressField.setAccessible(true); Field broadcastField = IAClass.getDeclaredField("broadcast"); broadcastField.setAccessible(true); Field maskLengthField = IAClass.getDeclaredField("maskLength"); maskLengthField.setAccessible(true); ia = ctr.newInstance(); addressField.set(ia, address); broadcastField.set(ia, broadcast); maskLengthField.setShort(ia, prefixlength); return ia; } catch (NoSuchFieldException nsfe) { nsfe.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InstantiationException ie) { ie.printStackTrace(); } catch (IllegalAccessException iae) { iae.printStackTrace(); } catch (InvocationTargetException ite) { ite.printStackTrace(); } return null; }
@Test public void testConstructorIsPrivate() throws Exception { Constructor<GherkinFactory> constructor = GherkinFactory.class.getDeclaredConstructor(); Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(); }
/** * Create an instance of the given class * @param className the name of the class * @return a dynamically created instance of the given class */ public static Object createInstance(String className) { Object retv = null; try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class<?> theFilterClass = Class.forName(className, true, classLoader); Constructor<?> meth = theFilterClass.getDeclaredConstructor(argArray); meth.setAccessible(true); retv = meth.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } return retv; }
private static Constructor<?> getConstructor(Class<?> c, Class<?>... types) { try { return (c == null) ? null : c.getDeclaredConstructor(types); } catch (NoSuchMethodException x) { throw new AssertionError(x); } }
/** * for example CDI in need for such constructors to create proxy objects. */ public static void assertProtectedConstructor(Class<?> clazz) { try { Constructor constructor = clazz.getDeclaredConstructor(); Assert.assertTrue(Modifier.isProtected(constructor.getModifiers())); constructor.setAccessible(true); Assert.assertNotNull(constructor.newInstance()); } catch (Exception e) { throw new IllegalStateException(e); } }
public static DevSupportManager create( Context applicationContext, ReactInstanceDevCommandsHandler reactInstanceCommandsHandler, @Nullable String packagerPathForJSBundleName, boolean enableOnCreate, @Nullable RedBoxHandler redBoxHandler) { if (!enableOnCreate) { return new DisabledDevSupportManager(); } try { // ProGuard is surprisingly smart in this case and will keep a class if it detects a call to // Class.forName() with a static string. So instead we generate a quasi-dynamic string to // confuse it. String className = new StringBuilder(DEVSUPPORT_IMPL_PACKAGE) .append(".") .append(DEVSUPPORT_IMPL_CLASS) .toString(); Class<?> devSupportManagerClass = Class.forName(className); Constructor constructor = devSupportManagerClass.getConstructor( Context.class, ReactInstanceDevCommandsHandler.class, String.class, boolean.class, RedBoxHandler.class); return (DevSupportManager) constructor.newInstance( applicationContext, reactInstanceCommandsHandler, packagerPathForJSBundleName, true, redBoxHandler); } catch (Exception e) { throw new RuntimeException( "Requested enabled DevSupportManager, but DevSupportManagerImpl class was not found" + " or could not be created", e); } }
public void testPatchSuperclassWithArray() throws Exception { Class<?> c = new L().loadClass(CAPI2.class.getName()); assertNotSame(c, CAPI2.class); Class s = c.getSuperclass(); assertEquals(CompatAPI2.class.getName(), s.getName()); Constructor<?> init = c.getConstructor(String[].class); init.newInstance((Object)new String[] {"a","b"}); }