List of usage examples for java.lang.reflect Constructor newInstance
@CallerSensitive @ForceInline public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
From source file:net.sf.ideais.ApplicationManager.java
/** * Load an application adapter./*w w w . j av a 2s . c om*/ * * @param clazz The class for the application adapter. * @param conf The configuration to be used to load the application adapter. * @return The application adapter or null if couldn't load any. */ private Application loadApplication(Class<? extends Application> clazz, Configuration conf) { Application app = null; log.debug("Loading " + clazz.getName() + " application adapter"); try { Constructor<? extends Application> constructor = clazz.getConstructor(Configuration.class); app = constructor.newInstance(conf); } catch (NoSuchMethodException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } if (app == null) { log.error("Couldn't load " + clazz.getName() + " application adapter"); } else { log.debug("Loaded application adapter " + clazz.getName()); } return app; }
From source file:it.geosolutions.geobatch.annotations.GenericActionService.java
/** * Istantiate an action class from the Class type and the ActionConfig provided. * <p/>// w w w . jav a 2 s . c o m * Once the class is instantiated: <ol> * <li>{@code @autowire} fields are autowired</li> * <li>{@code afterPropertiesSet()} is called if {@code InitializingBean} is declared</li> * </ol> * @param actionClass * @param actionConfig * @return */ public <T extends BaseAction<? extends EventObject>> T createAction(Class<T> actionClass, ActionConfiguration actionConfig) { try { LOGGER.info("Instantiating action " + actionClass.getSimpleName()); Constructor<T> constructor = actionClass.getConstructor(actionConfig.getClass()); T newInstance = constructor.newInstance(actionConfig); ((AbstractRefreshableApplicationContext) applicationContext).getBeanFactory().autowireBean(newInstance); if (InitializingBean.class.isAssignableFrom(actionClass)) { ((InitializingBean) newInstance).afterPropertiesSet(); } return newInstance; } catch (Exception e) { if (LOGGER.isErrorEnabled()) { LOGGER.error(e.getLocalizedMessage(), e); } throw new IllegalStateException("A fatal error occurred while instantiate the action class " + actionClass.getSimpleName() + ": " + e.getLocalizedMessage()); } }
From source file:com.scaleunlimited.cascading.DatumCompilerTest.java
@Test public void testUUID() throws Exception { CompiledDatum result = DatumCompiler.generate(MyUUIDDatumTemplate.class); File baseDir = new File("build/test/DatumCompilerTest/testUUID/"); FileUtils.deleteDirectory(baseDir);/*from w w w. j av a 2 s. co m*/ File srcDir = new File(baseDir, result.getPackageName().replaceAll("\\.", "/")); assertTrue(srcDir.mkdirs()); File codeFile = new File(srcDir, result.getClassName() + ".java"); OutputStream os = new FileOutputStream(codeFile); IOUtils.write(result.getClassCode(), os, "UTF-8"); os.close(); // Compile with Janino, give it a try. We have Janino since // it's a cascading dependency, but probably want to add a test // dependency on it. ClassLoader cl = new JavaSourceClassLoader(this.getClass().getClassLoader(), // parentClassLoader new File[] { baseDir }, // optionalSourcePath (String) null // optionalCharacterEncoding ); // WARNING - we have to use xxxDatumTemplate as the base name, so that the code returned // by the compiler is for type xxxDatum. Otherwise when we try to load the class here, // we'll likely get the base (template) class, which will mask our generated class. Class clazz = cl.loadClass(result.getPackageName() + "." + result.getClassName()); assertEquals("MyUUIDDatum", clazz.getSimpleName()); Constructor c = clazz.getConstructor(UUID.class); BaseDatum datum = (BaseDatum) c.newInstance(UUID.randomUUID()); // Verify that it can be serialized with Hadoop. // TODO figure out why Hadoop serializations aren't available??? /* BasePlatform testPlatform = new HadoopPlatform(DatumCompilerTest.class); Tap tap = testPlatform.makeTap( testPlatform.makeBinaryScheme(datum.getFields()), testPlatform.makePath("build/test/DatumCompilerTest/testSimpleSchema/")); TupleEntryCollector writer = tap.openForWrite(testPlatform.makeFlowProcess()); writer.add(datum.getTuple()); writer.close(); TupleEntryIterator iter = tap.openForRead(testPlatform.makeFlowProcess()); TupleEntry te = iter.next(); // TODO how to test round-trip? */ }
From source file:iddb.core.model.dao.DAOFactory.java
/** * @param key/* www. ja v a 2 s . c o m*/ * @param value * @return * @throws Exception * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException */ @SuppressWarnings({ "rawtypes", "unchecked" }) private Object createCachedInstance(String iface, Object impl) throws Exception { String[] ifacePart = StringUtils.split(iface, "."); String ifaceName = ifacePart[ifacePart.length - 1]; log.debug("Getting cached instance for {} - {}", iface, ifaceName); ClassLoader loader = this.getClass().getClassLoader(); try { Class clz = loader.loadClass("iddb.core.model.dao.cached." + ifaceName + "Cached"); Constructor cons = clz.getConstructor(new Class[] { Class.forName(iface) }); return cons.newInstance(impl); } catch (SecurityException e) { log.warn("No cached implementation found for {} - {}", ifaceName, e.getMessage()); throw new Exception(e); } catch (IllegalArgumentException e) { log.warn("No cached implementation found for {} - {}", ifaceName, e.getMessage()); throw new Exception(e); } catch (ClassNotFoundException e) { log.warn("No cached implementation found for {} - {}", ifaceName, e.getMessage()); throw new Exception(e); } catch (NoSuchMethodException e) { log.warn("No cached implementation found for {} - {}", ifaceName, e.getMessage()); throw new Exception(e); } catch (InstantiationException e) { log.warn("No cached implementation found for {} - {}", ifaceName, e.getMessage()); throw new Exception(e); } catch (IllegalAccessException e) { log.warn("No cached implementation found for {} - {}", ifaceName, e.getMessage()); throw new Exception(e); } catch (InvocationTargetException e) { e.printStackTrace(); log.warn("No cached implementation found for {} - {}", ifaceName, e.getMessage()); throw new Exception(e); } }
From source file:com.baidu.terminator.manager.service.LinkControlServiceImpl.java
private <T> T getPluginInstance(Link link, Class<T> clazz) { try {/*from ww w . j av a2s . c om*/ Constructor<T> constructor = clazz.getConstructor(Link.class); T plugin = constructor.newInstance(link); return plugin; } catch (SecurityException e) { throw new SignerInitializationException("InitializationFail", e.getCause()); } catch (IllegalArgumentException e) { throw new SignerInitializationException("InitializationFail", e.getCause()); } catch (NoSuchMethodException e) { throw new SignerInitializationException("InitializationFail", e.getCause()); } catch (InstantiationException e) { throw new SignerInitializationException("InitializationFail", e.getCause()); } catch (IllegalAccessException e) { throw new SignerInitializationException("InitializationFail", e.getCause()); } catch (InvocationTargetException e) { throw new SignerInitializationException("InitializationFail", e.getCause()); } }
From source file:ch.sdi.plugins.oxwall.profile.OxQuestionFactory.java
/** * Instantiates a custom oxwall ProfileQuestion type. * <p>/*from ww w. j a va2 s. co m*/ * see properties ox.target.qn.xxxx). For example: * <pre> * ox.target.qn.person.gender=custom:gendermap:sex * </pre> * <p> * @param aBeanName * the name of the implementing bean (in fact its the name parameter of the OxCustomQuestion * annotation). This corresponds to the second parameter of the property value. * @param aQuestionName * the name of the question. This corresponds to the third parameter of the property value. * @param aPersonKey * The key in the person PropertySource under which the corresponding value will be stored. * @return * @throws SdiException */ public OxProfileQuestion getCustomQuestion(String aBeanName, String aQuestionName, String aPersonKey) throws SdiException { Collection<Class<OxProfileQuestion>> candidates = ClassUtil.findCandidatesByAnnotation( OxProfileQuestion.class, OxCustomQuestion.class, "ch.sdi.plugins.oxwall"); for (Class<OxProfileQuestion> clazz : candidates) { myLog.trace("found candidate for custom question: " + clazz.getName()); OxCustomQuestion ann = clazz.getAnnotation(OxCustomQuestion.class); if (!ann.value().endsWith(aBeanName)) { myLog.trace("candidate has not the desired bean name (" + aBeanName + ") but: " + ann.value()); continue; } // if !ann.value().endsWith( "beanName" ) myLog.trace("found custom question class with beanName(" + aBeanName + "): " + clazz.getName()); try { Constructor<OxProfileQuestion> constructor = clazz .getConstructor(new Class<?>[] { String.class, String.class }); return constructor.newInstance(new Object[] { aQuestionName, aPersonKey }); } catch (Throwable t) { throw new SdiException("missing desired constructor found custom question class with" + " beanName(" + aBeanName + "): " + clazz.getName(), SdiException.EXIT_CODE_CONFIG_ERROR); } } throw new SdiException("No suitable custom question found. BeanName: " + aBeanName, SdiException.EXIT_CODE_CONFIG_ERROR); }
From source file:com.ewcms.web.pubsub.PubsubServlet.java
private PubsubSenderable createPubsubSender(String path) { String name = null;// w w w. java 2 s . c om if (StringUtils.indexOf(path, '/') == -1) { name = pathSender.get(path); } else { String root = StringUtils.substringBeforeLast(path, "/"); name = pathSender.get(root); if (name == null) { String middle = StringUtils.substringAfter(root, "/"); name = pathSender.get(middle); } } if (StringUtils.isNotBlank(name)) { try { Class<?> clazz = Class.forName(name); Class<?>[] argsClass = new Class<?>[] { String.class, ServletContext.class }; Constructor<?> cons = clazz.getConstructor(argsClass); return (PubsubSenderable) cons.newInstance(new Object[] { path, this.getServletContext() }); } catch (Exception e) { logger.error("PubsubSender create error:{}", e.toString()); } } return new NoneSender(); }
From source file:org.jboss.arquillian.spring.integration.javaconfig.container.AnnotationRemoteApplicationContextProducer.java
/** * <p>Creates new instance of the given type.</p> * * @param applicationContextClass the application context class * @param ctor the constructor to use * @param params the constructor parameters * @param <T> the type of the application context * * @return the created instance of {@link ApplicationContext} *///from w w w . ja va2s . c o m private <T extends ApplicationContext> T createInstance(Class<T> applicationContextClass, Constructor<T> ctor, Object... params) { try { return ctor.newInstance(params); } catch (InstantiationException e) { throw new RuntimeException("Could not create instance of " + applicationContextClass.getName(), e); } catch (IllegalAccessException e) { throw new RuntimeException("Could not create instance of " + applicationContextClass.getName(), e); } catch (InvocationTargetException e) { throw new RuntimeException("Could not create instance of " + applicationContextClass.getName(), e); } }
From source file:com.qualogy.qafe.business.resource.java.JavaClass.java
private Object createInstance(Class<?> clazz, JavaResource resource) { Object instance = null;/*w w w.jav a2 s . c o m*/ try { // List<Parameter> arguments = resource.getArguments(); // if(arguments!=null){ // Collections.sort(arguments); // for (Parameter argument : arguments) { // argument.get // } // } Constructor<?> constructor = clazz.getDeclaredConstructor(new Class[] {}); constructor.setAccessible(true); instance = constructor.newInstance(new Object[] {}); } catch (NoSuchMethodException e) { throw new ResourceInitializationException("possible error; no default constructor", e); } catch (InvocationTargetException e) { throw new ResourceInitializationException(e); } catch (IllegalAccessException e) { throw new ResourceInitializationException(e); } catch (InstantiationException e) { throw new ResourceInitializationException(e); } return instance; }
From source file:fitnesse.responders.ResponderFactory.java
private Responder newResponderInstance(Class<?> responderClass) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { try {// w w w . j a v a 2 s .co m Constructor<?> constructor = responderClass.getConstructor(String.class); return (Responder) constructor.newInstance(rootPath); } catch (NoSuchMethodException e) { Constructor<?> constructor = responderClass.getConstructor(); return (Responder) constructor.newInstance(); } }