List of usage examples for java.lang Class getDeclaredConstructor
@CallerSensitive public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
From source file:com.netspective.sparx.util.xml.XmlSource.java
public void saveXML(String fileName) { /* we use reflection so that org.apache.xml.serialize.* is not a package requirement */ OutputStream os = null;//from ww w. j a v a 2 s . co m try { Class serializerCls = Class.forName("org.apache.xml.serialize.XMLSerializer"); Class outputFormatCls = Class.forName("org.apache.xml.serialize.OutputFormat"); Constructor serialCons = serializerCls .getDeclaredConstructor(new Class[] { OutputStream.class, outputFormatCls }); Constructor outputCons = outputFormatCls.getDeclaredConstructor(new Class[] { Document.class }); os = new FileOutputStream(fileName); Object outputFormat = outputCons.newInstance(new Object[] { xmlDoc }); Method indenting = outputFormatCls.getMethod("setIndenting", new Class[] { boolean.class }); indenting.invoke(outputFormat, new Object[] { new Boolean(true) }); Object serializer = serialCons.newInstance(new Object[] { os, outputFormat }); Method serialize = serializerCls.getMethod("serialize", new Class[] { Document.class }); serialize.invoke(serializer, new Object[] { xmlDoc }); } catch (Exception e) { throw new RuntimeException("Unable to save '" + fileName + "': " + e); } finally { try { if (os != null) os.close(); } catch (Exception e) { } } }
From source file:com.stratuscom.harvester.deployer.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); }/* w ww . j a va 2 s.c om*/ Constructor constructor = clazz.getDeclaredConstructor(new Class[] { String[].class, lifeCycleClass }); constructor.setAccessible(true); return constructor.newInstance(parms, null); }
From source file:org.evosuite.testcarver.testcase.EvoTestCaseCodeGenerator.java
@Override public void createMethodCallStmt(final CaptureLog log, final int logRecNo) { if (log == null) throw new IllegalArgumentException("captured log must not be null"); if (logRecNo <= -1) throw new IllegalArgumentException("log record number is invalid: " + logRecNo); if (isMaximumLengthReached()) return;/*from w ww . j a v a 2 s . c o m*/ // assumption: all necessary statements are created and there is one variable for each referenced object final int oid = log.objectIds.get(logRecNo); final Object[] methodArgs = log.params.get(logRecNo); final String methodName = log.methodNames.get(logRecNo); Class<?> type; try { final String typeName = log.getTypeName(oid); type = getClassForName(typeName); logger.debug("Creating method call statement for call to method {}.{}", typeName, methodName); final Class<?>[] methodParamTypeClasses = getMethodParamTypeClasses(log, logRecNo); final ArrayList<VariableReference> args = getArguments(methodArgs, methodParamTypeClasses); if (CaptureLog.OBSERVED_INIT.equals(methodName)) { // Person var0 = new Person(); final ConstructorStatement constStmt = new ConstructorStatement(testCase, new GenericConstructor(type.getDeclaredConstructor(methodParamTypeClasses), type), args); this.oidToVarRefMap.put(oid, testCase.addStatement(constStmt)); } else { //------------------ handling for ordinary method calls e.g. var1 = var0.doSth(); final Object returnValue = log.returnValues.get(logRecNo); if (CaptureLog.RETURN_TYPE_VOID.equals(returnValue)) { GenericMethod genericMethod = new GenericMethod( this.getDeclaredMethod(type, methodName, methodParamTypeClasses), type); MethodStatement m = new MethodStatement(testCase, genericMethod, this.oidToVarRefMap.get(oid), args); testCase.addStatement(m); } else { // final org.objectweb.asm.Type returnType = org.objectweb.asm.Type.getReturnType(methodDesc); logger.debug("Callee: {} ({})", this.oidToVarRefMap.get(oid), this.oidToVarRefMap.keySet()); // Person var0 = var.getPerson(); final MethodStatement m = new MethodStatement(testCase, new GenericMethod(this.getDeclaredMethod(type, methodName, methodParamTypeClasses), type), this.oidToVarRefMap.get(oid), args); final Integer returnValueOID = (Integer) returnValue; this.oidToVarRefMap.put(returnValueOID, testCase.addStatement(m)); } } } catch (NoSuchMethodException e) { logger.info("Method not found; this may happen e.g. if an exception is thrown in the constructor"); return; } catch (final Exception e) { logger.info("Error at log record number {}: {}", logRecNo, e.toString()); logger.info("Test case so far: " + testCase.toCode()); logger.info(log.toString()); CodeGeneratorException.propagateError(e, "[logRecNo = %s] - an unexpected error occurred while creating method call stmt for %s.", logRecNo, methodName); } }
From source file:org.apache.hadoop.hive.metastore.MetaStoreUtils.java
/** * Create an object of the given class.// w w w.j a v a 2 s .c o m * @param theClass * @param parameterTypes * an array of parameterTypes for the constructor * @param initargs * the list of arguments for the constructor */ public static <T> T newInstance(Class<T> theClass, Class<?>[] parameterTypes, Object[] initargs) { // Perform some sanity checks on the arguments. if (parameterTypes.length != initargs.length) { throw new IllegalArgumentException( "Number of constructor parameter types doesn't match number of arguments"); } for (int i = 0; i < parameterTypes.length; i++) { Class<?> clazz = parameterTypes[i]; if (initargs[i] != null && !(clazz.isInstance(initargs[i]))) { throw new IllegalArgumentException("Object : " + initargs[i] + " is not an instance of " + clazz); } } try { Constructor<T> meth = theClass.getDeclaredConstructor(parameterTypes); meth.setAccessible(true); return meth.newInstance(initargs); } catch (Exception e) { throw new RuntimeException("Unable to instantiate " + theClass.getName(), e); } }
From source file:nz.co.senanque.madura.configuration.ConstructorBeanFactory.java
public synchronized Object createBean(Class beanClass, BeanDeclaration decl, Object param) throws Exception { Map m = decl.getBeanProperties(); XMLBeanDeclaration xmlDecl = (XMLBeanDeclaration) decl; ConfigurationNode n = xmlDecl.getNode(); String nodeName = n.getName(); n = n.getParentNode();/* ww w . ja v a 2 s . c om*/ while (n != null) { if (n.getName() != null) nodeName = n.getName() + "/" + nodeName; n = n.getParentNode(); } Object bean = beans.get(nodeName); if (bean != null) { // Yes, there is already an instance return bean; } else { // No, create it now (done by the super class) List<Class> constructorClasses = new ArrayList<Class>(); List<Object> constructorArguments = new ArrayList<Object>(); Object o = m.get("constructor-arg"); if (o != null) { constructorClasses.add(o.getClass()); constructorArguments.add(o); } o = m.get("constructor-arg0"); if (o != null) { constructorClasses.add(o.getClass()); constructorArguments.add(o); } for (int i = 1; i < 10; i++) { o = m.get("constructor-arg" + i); if (o == null) break; constructorClasses.add(o.getClass()); constructorArguments.add(o); } Constructor constructor = beanClass .getDeclaredConstructor(constructorClasses.toArray(new Class[constructorClasses.size()])); bean = constructor.newInstance(constructorArguments.toArray(new Object[constructorArguments.size()])); // Store it in map beans.put(nodeName, bean); return bean; } }
From source file:com.m4rc310.cb.builders.ComponentBuilder.java
private Object getNewInstanceObjectAnnotated(String ref, Object... args) { Object ret = null;/*w w w .j ava 2 s . c o m*/ try { for (Class in : ClassScan.findAll().annotatedWith(Adialog.class).recursively() .in(conf.get("path_gui").toString(), "com.m4rc310.gui")) { Adialog ad = (Adialog) in.getDeclaredAnnotation(Adialog.class); if (ad.ref().equals(ref)) { if (ret != null) { throw new Exception(String.format("H mais de uma classe refernciada como [%s]!", ref)); } Class[] types = new Class[args.length]; Constructor constructor = null; for (int i = 0; i < args.length; i++) { types[i] = args[i].getClass(); Class type = args[i].getClass(); for (Class ai : type.getInterfaces()) { try { constructor = in.getDeclaredConstructor(ai); break; } catch (NoSuchMethodException | SecurityException e) { infoError(e); } } } constructor = constructor == null ? in.getDeclaredConstructor(types) : constructor; // Constructor constructor = in.getDeclaredConstructor(types); constructor.setAccessible(true); ret = constructor.newInstance(args); } } return ret; } catch (Exception e) { infoError(e); throw new UnsupportedOperationException(e); } }
From source file:com.opera.core.systems.OperaSettings.java
/** * Get the runner to use for starting and managing the Opera instance. * * @return the current runner//from w w w . jav a 2s.co m */ public OperaRunner getRunner() { String klassName = (String) options.get(RUNNER).getValue(); // If no runner is set, use the default one if (klassName == null) { setRunner(OperaLauncherRunner.class); return getRunner(); } Class<?> klass; try { klass = Class.forName(klassName); } catch (ClassNotFoundException e) { throw new WebDriverException("Unable to find runner class on classpath: " + klassName); } Constructor constructor; try { constructor = klass.getDeclaredConstructor(OperaSettings.class); } catch (NoSuchMethodException e) { throw new WebDriverException("Invalid constructor in runner: " + klass.getName()); } OperaRunner runner; try { runner = (OperaRunner) constructor.newInstance(this); } catch (InstantiationException e) { throw new WebDriverException("Unable to create new instance of runner", e); } catch (IllegalAccessException e) { throw new WebDriverException("Denied access to runner: " + klass.getName()); } catch (InvocationTargetException e) { throw new WebDriverException("Runner threw exception on construction", e); } return runner; }
From source file:it.cnr.icar.eric.client.xml.registry.jaas.LoginModuleManager.java
/** * This method is used to get the CallbackHandler from the bundled * properties file. It reads the/*from w w w . j av a 2 s . com*/ * jaxr-ebxml.security.jaas.callbackHandlerClassName property. * If this file or property does not exist, it defaults to * com.sun.xml.registry.client.jaas.DialogAuthenticationCallbackHandler. * * @return * An instance of the CallbackHandler interface */ public CallbackHandler getCallbackHandler() throws JAXRException { log.trace("start getting CallbackHandler name"); if (callbackHandler == null) { Properties properties = JAXRUtility.getBundledClientProperties(); String callbackHandlerClassName = properties .getProperty(ROOT_PROPERTY_NAME + ".security.jaas.callbackHandlerClassName"); // over ride with system properties. The system property is used // by the thick client. The file property is used by the thin client String callbackHandlerClassNameFromSystem = System .getProperty(ROOT_PROPERTY_NAME + ".security.jaas.callbackHandlerClassName"); if (callbackHandlerClassNameFromSystem != null) { callbackHandlerClassName = callbackHandlerClassNameFromSystem; } if (callbackHandlerClassName != null) { Class<?> clazz = null; try { clazz = Class.forName(callbackHandlerClassName); } catch (ClassNotFoundException ex) { log.error(ex); throw new JAXRException(JAXRResourceBundle.getInstance().getString( "message.error.not.instantiate.CallbackHandler", new Object[] { callbackHandlerClassName })); } Class<?>[] clazzes = new Class[1]; clazzes[0] = java.awt.Frame.class; Constructor<?> constructor = null; try { constructor = clazz.getDeclaredConstructor(clazzes); Object[] objs = new Object[1]; Frame frame = getParentFrame(); if (frame != null) { objs[0] = frame; } callbackHandler = (CallbackHandler) constructor.newInstance(objs); } catch (NoSuchMethodException ex) { log.debug("Could not find constructor that takes a Frame " + "parameter. Trying default constructor"); // use default constructor instead try { callbackHandler = (CallbackHandler) Class.forName(callbackHandlerClassName).newInstance(); } catch (Throwable t) { log.error(t); throw new JAXRException(JAXRResourceBundle.getInstance().getString( "message.error.not.instantiate.CallbackHandler.classpath", new Object[] { callbackHandlerClassName })); } } catch (Throwable t) { log.error(t.getMessage()); throw new JAXRException(JAXRResourceBundle.getInstance().getString( "message.error.not.instantiate.CallbackHandler", new Object[] { callbackHandlerClassName })); } } if (callbackHandler == null) { log.info(JAXRResourceBundle.getInstance().getString("message.UsingDefaultCallbackHandler")); // If set, user default CallbackHandler provided by user if (defaultCallbackHandler != null) { callbackHandler = defaultCallbackHandler; } else // Use default CallbackHandler that loads credentials // from client-side keystore file. { callbackHandler = new ThinClientCallbackHandler(); } } log.info(JAXRResourceBundle.getInstance().getString("message.CallbackHandlerName", new Object[] { callbackHandler.getClass().getName() })); } log.trace("finish getting CallbackHandler name"); return callbackHandler; }
From source file:org.apache.catalina.core.StandardDefaultContext.java
/** * Install the StandardContext portion of the DefaultContext * configuration into current Context.//from w ww . j a v a2 s.c o m * * @param context current web application context */ public void installDefaultContext(Context context) { if (context instanceof StandardContext) { ((StandardContext) context).setUseNaming(isUseNaming()); ((StandardContext) context).setSwallowOutput(getSwallowOutput()); ((StandardContext) context).setCachingAllowed(isCachingAllowed()); ((StandardContext) context).setCacheTTL(getCacheTTL()); ((StandardContext) context).setCacheMaxSize(getCacheMaxSize()); ((StandardContext) context).setAllowLinking(isAllowLinking()); ((StandardContext) context).setCaseSensitive(isCaseSensitive()); ((StandardContext) context).setManagerChecksFrequency(getManagerChecksFrequency()); if (!contexts.containsKey(context)) { ((StandardContext) context).addLifecycleListener(this); } Enumeration lifecycleListeners = lifecycle.elements(); while (lifecycleListeners.hasMoreElements()) { ((StandardContext) context) .addLifecycleListener((LifecycleListener) lifecycleListeners.nextElement()); } } if (!context.getPrivileged() && loader != null) { ClassLoader parentClassLoader = context.getParent().getParentClassLoader(); Class clazz = loader.getClass(); Class types[] = { ClassLoader.class }; Object args[] = { parentClassLoader }; try { Constructor constructor = clazz.getDeclaredConstructor(types); Loader context_loader = (Loader) constructor.newInstance(args); context_loader.setDelegate(loader.getDelegate()); context_loader.setReloadable(loader.getReloadable()); if (loader instanceof WebappLoader) { ((WebappLoader) context_loader).setDebug(((WebappLoader) loader).getDebug()); ((WebappLoader) context_loader).setLoaderClass(((WebappLoader) loader).getLoaderClass()); } context.setLoader(context_loader); } catch (Exception e) { throw new IllegalArgumentException( "DefaultContext custom Loader install failed, Exception: " + e.getMessage()); } } }