Java Code Examples for java.lang.reflect.Constructor#newInstance()
The following examples show how to use
java.lang.reflect.Constructor#newInstance() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ORBImpl.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
public void initBadServerIdHandler() { synchronized (this) { checkShutdownState(); } synchronized (badServerIdHandlerAccessLock) { Class cls = configData.getBadServerIdHandler() ; if (cls != null) { try { Class[] params = new Class[] { org.omg.CORBA.ORB.class }; java.lang.Object[] args = new java.lang.Object[]{this}; Constructor cons = cls.getConstructor(params); badServerIdHandler = (BadServerIdHandler) cons.newInstance(args); } catch (Exception e) { throw wrapper.errorInitBadserveridhandler( e ) ; } } } }
Example 2
Source File: ZNRecordUtil.java From helix with Apache License 2.0 | 6 votes |
public static <T extends Object> Map<String, T> convertListToTypedMap(List<ZNRecord> recordList, Class<T> clazz) { Map<String, T> map = new HashMap<String, T>(); for (ZNRecord record : recordList) { if (record.getId() == null) { logger.error("Invalid record: Id missing in " + record); continue; } try { Constructor<T> constructor = clazz.getConstructor(new Class[] { ZNRecord.class }); T instance = constructor.newInstance(record); map.put(record.getId(), instance); } catch (Exception e) { logger.error("Error creating an Object of type:" + clazz.getCanonicalName(), e); } } return map; }
Example 3
Source File: Connection.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
private Object createInetSocketAddress(String host, int port) throws NoSuchMethodException { try { Class<?> inetSocketAddressClass = Class.forName("java.net.InetSocketAddress"); Constructor<?> inetSocketAddressCons = inetSocketAddressClass.getConstructor(new Class<?>[]{ String.class, int.class}); return inetSocketAddressCons.newInstance(new Object[]{ host, new Integer(port)}); } catch (ClassNotFoundException | InstantiationException | InvocationTargetException | IllegalAccessException e) { throw new NoSuchMethodException(); } }
Example 4
Source File: CategoryValueDynamicExtractor.java From seldon-server with Apache License 2.0 | 6 votes |
@Override public String extract(AttributeDetail attributeDetail, String url, Document articleDoc) throws Exception { String attrib_value = null; if ((attributeDetail.extractor_args != null) && (attributeDetail.extractor_args.size() == 1)) { String categoryClassPrefix = attributeDetail.extractor_args.get(0); if (StringUtils.isNotBlank(categoryClassPrefix)) { String className = "io.seldon.importer.articles.category." + categoryClassPrefix + "CategoryExtractor"; Class<?> clazz = Class.forName(className); Constructor<?> ctor = clazz.getConstructor(); CategoryExtractor extractor = (CategoryExtractor) ctor.newInstance(); attrib_value = extractor.getCategory(url, articleDoc); } } return attrib_value; }
Example 5
Source File: Git.java From git-client-plugin with MIT License | 5 votes |
private GitClient initMockClient(String className, String exe, EnvVars env, File f, TaskListener listener) throws RuntimeException { try { final Class<?> it = Class.forName(className); final Constructor<?> constructor = it.getConstructor(String.class, EnvVars.class, File.class, TaskListener.class); return (GitClient)constructor.newInstance(exe, env, f, listener); } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InstantiationException | NoSuchMethodException | SecurityException | InvocationTargetException e) { throw new RuntimeException("Unable to initialize mock GitClient " + className, e); } }
Example 6
Source File: CodeGenerator.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public static boolean targetExists(String language) { String targetName = "org.antlr.v4.codegen.target."+language+"Target"; try { Class<? extends Target> c = Class.forName(targetName).asSubclass(Target.class); Constructor<? extends Target> ctor = c.getConstructor(CodeGenerator.class); CodeGenerator gen = new CodeGenerator(language); Target target = ctor.newInstance(gen); return target.templatesExist(); } catch (Exception e) { // ignore errors; we're detecting presence only } return false; }
Example 7
Source File: ProxyArrayCalls.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
/** * 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; }
Example 8
Source File: IgfsUtils.java From ignite with Apache License 2.0 | 5 votes |
/** * Construct new IGFS exception passing specified message and cause. * * @param cls Class. * @param msg Message. * @param cause Cause. * @return New IGFS exception. */ public static IgfsException newIgfsException(Class<? extends IgfsException> cls, String msg, Throwable cause) { try { Constructor<? extends IgfsException> ctor = cls.getConstructor(String.class, Throwable.class); return ctor.newInstance(msg, cause); } catch (ReflectiveOperationException e) { throw new IgniteException("Failed to create IGFS exception: " + cls.getName(), e); } }
Example 9
Source File: ActionFactory.java From ankush with GNU Lesser General Public License v3.0 | 5 votes |
/** * Gets the actionable object. * * @param className * the class name * @return the actionable object */ private static Actionable getActionableObject(String className) { com.impetus.ankush.agent.action.Actionable obj = null; try { Class<?> clazz = Class.forName(className); Constructor<?> co = clazz.getConstructor(); obj = (com.impetus.ankush.agent.action.Actionable) (co .newInstance(null)); } catch (Exception e) { System.err.println(e.getMessage()); } return obj; }
Example 10
Source File: CommonsUtilTest.java From kardio with Apache License 2.0 | 5 votes |
@Test public void testPrivateConstructor() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor<CommonsUtil> constructor = CommonsUtil.class.getDeclaredConstructor(); assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(); }
Example 11
Source File: RelJson.java From Bats with Apache License 2.0 | 5 votes |
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 | ClassCastException | InvocationTargetException | IllegalAccessException e) { throw new RuntimeException( "while invoking constructor for type '" + type + "'", e); } }
Example 12
Source File: NetUtils.java From distributedlog with Apache License 2.0 | 5 votes |
/** * Get the dns resolver from class <code>resolverClassName</code> with optional * <code>hostRegionOverrides</code>. * * <p>It would try to load the class with the constructor with <code>hostRegionOverrides</code>. * If it fails, it would fall back to load the class with default empty constructor. * The interpretion of <code>hostRegionOverrides</code> is up to the implementation. * * @param resolverCls * resolver class * @param hostRegionOverrides * host region overrides * @return dns resolver */ public static DNSToSwitchMapping getDNSResolver(Class<? extends DNSToSwitchMapping> resolverCls, String hostRegionOverrides) { // first try to construct the dns resolver with overrides Constructor<? extends DNSToSwitchMapping> constructor; Object[] parameters; try { constructor = resolverCls.getDeclaredConstructor(String.class); parameters = new Object[] { hostRegionOverrides }; } catch (NoSuchMethodException nsme) { // no constructor with overrides try { constructor = resolverCls.getDeclaredConstructor(); parameters = new Object[0]; } catch (NoSuchMethodException nsme1) { throw new RuntimeException("Unable to find constructor for dns resolver " + resolverCls, nsme1); } } constructor.setAccessible(true); try { return constructor.newInstance(parameters); } catch (InstantiationException ie) { throw new RuntimeException("Unable to instantiate dns resolver " + resolverCls, ie); } catch (IllegalAccessException iae) { throw new RuntimeException("Illegal access to dns resolver " + resolverCls, iae); } catch (InvocationTargetException ite) { throw new RuntimeException("Unable to construct dns resolver " + resolverCls, ite); } }
Example 13
Source File: ExceptionClassTest.java From development with Apache License 2.0 | 5 votes |
/** * Test if all public API exceptions have a default constructor. */ @Test public void testExceptionDefaultConstructors() throws Exception { StringBuffer errors = new StringBuffer(); StringBuffer nonDefMessage = new StringBuffer(); List<Class<?>> classes = PackageClassReader.getClasses( CurrencyException.class, Throwable.class, ClassFilter.CLASSES_ONLY); for (Class<?> clazz : classes) { try { Constructor<?> declaredConstructor = clazz .getDeclaredConstructor(); Object instance = declaredConstructor.newInstance(); if (instance instanceof Throwable) { if (((Throwable) instance).getMessage() == null) { nonDefMessage.append(clazz.getSimpleName()); nonDefMessage.append('\n'); } } } catch (NoSuchMethodException e) { errors.append(e.getMessage()); errors.append('\n'); } } StringBuffer failures = new StringBuffer(); if (errors.length() > 0) { failures.append("Exceptions without default constructor:\n" + errors.toString()); } if (nonDefMessage.length() > 0) { failures.append("Exceptions without default message:\n" + nonDefMessage.toString()); } if (failures.length() > 0) { fail(failures.toString()); } }
Example 14
Source File: XMLSerialization.java From rapidminer-studio with GNU Affero General Public License v3.0 | 5 votes |
private XMLSerialization(ClassLoader classLoader) { try { Class<?> xStreamClass = Class.forName("com.thoughtworks.xstream.XStream"); Class<?> generalDriverClass = Class.forName("com.thoughtworks.xstream.io.HierarchicalStreamDriver"); Constructor<?> constructor = xStreamClass.getConstructor(generalDriverClass); Class<?> driverClass = Class.forName("com.thoughtworks.xstream.io.xml.XppDriver"); xStream = (com.thoughtworks.xstream.XStream) constructor.newInstance(driverClass.newInstance()); xStream.setMode(com.thoughtworks.xstream.XStream.ID_REFERENCES); // define default aliases here addAlias("IOContainer", IOContainer.class); addAlias("PolynominalAttribute", PolynominalAttribute.class); addAlias("BinominalAttribute", BinominalAttribute.class); addAlias("NumericalAttribute", NumericalAttribute.class); addAlias("PolynominalMapping", PolynominalMapping.class); addAlias("BinominalMapping", BinominalMapping.class); addAlias("NumericalStatistics", NumericalStatistics.class); addAlias("WeightedNumericalStatistics", WeightedNumericalStatistics.class); addAlias("NominalStatistics", NominalStatistics.class); addAlias("UnknownStatistics", UnknownStatistics.class); addAlias("SimpleAttributes", SimpleAttributes.class); addAlias("AttributeRole", AttributeRole.class); xStream.setClassLoader(classLoader); defineXMLAliasPairs(); } catch (Throwable e) { // TODO: Why are we catching Throwables? LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.tools.XMLSerialization.writing_initializing_xml_serialization_error", e), e); } }
Example 15
Source File: Averagable.java From rapidminer-studio with GNU Affero General Public License v3.0 | 5 votes |
/** Returns a (deep) clone of this averagable. */ @Override public Object clone() throws CloneNotSupportedException { try { Class<? extends Averagable> clazz = this.getClass(); Constructor<? extends Averagable> cloneConstructor = clazz.getConstructor(clazz); return cloneConstructor.newInstance(this); } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) { throw new CloneNotSupportedException("Cannot clone averagable: " + e.getMessage()); } }
Example 16
Source File: MozillaRhino1.java From ysoserial with MIT License | 4 votes |
public Object getObject(final String command) throws Exception { Class nativeErrorClass = Class.forName("org.mozilla.javascript.NativeError"); Constructor nativeErrorConstructor = nativeErrorClass.getDeclaredConstructor(); Reflections.setAccessible(nativeErrorConstructor); IdScriptableObject idScriptableObject = (IdScriptableObject) nativeErrorConstructor.newInstance(); Context context = Context.enter(); NativeObject scriptableObject = (NativeObject) context.initStandardObjects(); Method enterMethod = Context.class.getDeclaredMethod("enter"); NativeJavaMethod method = new NativeJavaMethod(enterMethod, "name"); idScriptableObject.setGetterOrSetter("name", 0, method, false); Method newTransformer = TemplatesImpl.class.getDeclaredMethod("newTransformer"); NativeJavaMethod nativeJavaMethod = new NativeJavaMethod(newTransformer, "message"); idScriptableObject.setGetterOrSetter("message", 0, nativeJavaMethod, false); Method getSlot = ScriptableObject.class.getDeclaredMethod("getSlot", String.class, int.class, int.class); Reflections.setAccessible(getSlot); Object slot = getSlot.invoke(idScriptableObject, "name", 0, 1); Field getter = slot.getClass().getDeclaredField("getter"); Reflections.setAccessible(getter); Class memberboxClass = Class.forName("org.mozilla.javascript.MemberBox"); Constructor memberboxClassConstructor = memberboxClass.getDeclaredConstructor(Method.class); Reflections.setAccessible(memberboxClassConstructor); Object memberboxes = memberboxClassConstructor.newInstance(enterMethod); getter.set(slot, memberboxes); NativeJavaObject nativeObject = new NativeJavaObject(scriptableObject, Gadgets.createTemplatesImpl(command), TemplatesImpl.class); idScriptableObject.setPrototype(nativeObject); BadAttributeValueExpException badAttributeValueExpException = new BadAttributeValueExpException(null); Field valField = badAttributeValueExpException.getClass().getDeclaredField("val"); Reflections.setAccessible(valField); valField.set(badAttributeValueExpException, idScriptableObject); return badAttributeValueExpException; }
Example 17
Source File: TransformMockUtil.java From hop with Apache License 2.0 | 4 votes |
public static <T extends BaseTransform, K extends ITransform, V extends ITransformData> T getTransform( Class<T> klass, TransformMockHelper<K, V> mock ) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Constructor<T> kons = klass.getConstructor( TransformMeta.class, ITransformData.class, int.class, PipelineMeta.class, Pipeline.class ); T transform = kons.newInstance( mock.transformMeta, mock.iTransformData, 0, mock.pipelineMeta, mock.pipeline ); return transform; }
Example 18
Source File: StandardProviderFactory.java From nifi-registry with Apache License 2.0 | 4 votes |
@Bean @Override public List<EventHookProvider> getEventHookProviders() { if (eventHookProviders == null) { eventHookProviders = new ArrayList<>(); if (providersHolder.get() == null) { throw new ProviderFactoryException("ProviderFactory must be initialized before obtaining a Provider"); } final Providers providers = providersHolder.get(); final List<org.apache.nifi.registry.provider.generated.Provider> jaxbHookProvider = providers.getEventHookProvider(); if(jaxbHookProvider == null || jaxbHookProvider.isEmpty()) { // no hook provided return eventHookProviders; } for (org.apache.nifi.registry.provider.generated.Provider hookProvider : jaxbHookProvider) { final String hookProviderClassName = hookProvider.getClazz(); EventHookProvider hook; try { final ClassLoader classLoader = extensionManager.getExtensionClassLoader(hookProviderClassName); if (classLoader == null) { throw new IllegalStateException("Extension not found in any of the configured class loaders: " + hookProviderClassName); } final Class<?> rawHookProviderClass = Class.forName(hookProviderClassName, true, classLoader); final Class<? extends EventHookProvider> hookProviderClass = rawHookProviderClass.asSubclass(EventHookProvider.class); final Constructor constructor = hookProviderClass.getConstructor(); hook = (EventHookProvider) constructor.newInstance(); performMethodInjection(hook, hookProviderClass); LOGGER.info("Instantiated EventHookProvider with class name {}", new Object[] {hookProviderClassName}); } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new ProviderFactoryException("Error creating EventHookProvider with class name: " + hookProviderClassName, e); } final ProviderConfigurationContext configurationContext = createConfigurationContext(hookProvider.getProperty()); hook.onConfigured(configurationContext); eventHookProviders.add(hook); LOGGER.info("Configured EventHookProvider with class name {}", new Object[] {hookProviderClassName}); } } return eventHookProviders; }
Example 19
Source File: MapperConstantsTest.java From mybatis-dynamic-query with Apache License 2.0 | 4 votes |
@Test(expected = InvocationTargetException.class) public void TestMapperConstants() throws Exception { Constructor<MapperConstants> c = MapperConstants.class.getDeclaredConstructor(); c.setAccessible(true); c.newInstance(); }
Example 20
Source File: OverlappingTestBase.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
/** * Adds current AWT control to container * <p>N.B.: if testEmbeddedFrame == true this method will also add EmbeddedFrame over Canvas * and it should be called <b>after</b> Frame.setVisible(true) call * @param container container to hold AWT component */ protected final void propagateAWTControls(Container container) { if (currentAwtControl != null) { container.add(currentAwtControl); } else { // embedded frame try { //create embedder Canvas embedder = new Canvas(); embedder.setBackground(Color.RED); embedder.setPreferredSize(new Dimension(150, 150)); container.add(embedder); container.setVisible(true); // create peer long frameWindow = 0; String getWindowMethodName = null; String eframeClassName = null; if (Toolkit.getDefaultToolkit().getClass().getName().contains("XToolkit")) { java.awt.Helper.addExports("sun.awt.X11", OverlappingTestBase.class.getModule()); getWindowMethodName = "getWindow"; eframeClassName = "sun.awt.X11.XEmbeddedFrame"; }else if (Toolkit.getDefaultToolkit().getClass().getName().contains(".WToolkit")) { java.awt.Helper.addExports("sun.awt.windows", OverlappingTestBase.class.getModule()); getWindowMethodName = "getHWnd"; eframeClassName = "sun.awt.windows.WEmbeddedFrame"; }else if (isMac) { java.awt.Helper.addExports("sun.lwawt", OverlappingTestBase.class.getModule()); java.awt.Helper.addExports("sun.lwawt.macosx", OverlappingTestBase.class.getModule()); eframeClassName = "sun.lwawt.macosx.CViewEmbeddedFrame"; } ComponentPeer peer = AWTAccessor.getComponentAccessor() .getPeer(embedder); if (!isMac) { Method getWindowMethod = peer.getClass().getMethod(getWindowMethodName); frameWindow = (Long) getWindowMethod.invoke(peer); } else { Method m_getPlatformWindowMethod = peer.getClass().getMethod("getPlatformWindow"); Object platformWindow = m_getPlatformWindowMethod.invoke(peer); Class classPlatformWindow = Class.forName("sun.lwawt.macosx.CPlatformWindow"); Method m_getContentView = classPlatformWindow.getMethod("getContentView"); Object contentView = m_getContentView.invoke(platformWindow); Class classContentView = Class.forName("sun.lwawt.macosx.CPlatformView"); Method m_getAWTView = classContentView.getMethod("getAWTView"); frameWindow = (Long) m_getAWTView.invoke(contentView); } Class eframeClass = Class.forName(eframeClassName); Constructor eframeCtor = eframeClass.getConstructor(long.class); EmbeddedFrame eframe = (EmbeddedFrame) eframeCtor.newInstance(frameWindow); setupControl(eframe); eframe.setSize(new Dimension(150, 150)); eframe.setVisible(true); // System.err.println(eframe.getSize()); } catch (Exception ex) { ex.printStackTrace(); fail("Failed to instantiate EmbeddedFrame: " + ex.getMessage()); } } }