List of usage examples for java.lang Class getConstructor
@CallerSensitive public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
From source file:Main.java
public static void main(String[] args) throws Exception { Class clazz = String.class; Constructor constructor = clazz.getConstructor(new Class[] { String.class }); String object = (String) constructor.newInstance(new Object[] { "Hello World!" }); System.out.println("String = " + object); constructor = clazz.getConstructor(new Class[] { StringBuilder.class }); object = (String) constructor.newInstance(new Object[] { new StringBuilder("Hello Universe!") }); System.out.println("String = " + object); }
From source file:Main.java
public static void main(String args[]) throws Exception { String name = "java.lang.String"; String methodName = "toLowerCase"; Class cl = Class.forName(name); java.lang.reflect.Constructor constructor = cl.getConstructor(new Class[] { String.class }); Object invoker = constructor.newInstance(new Object[] { "AAA" }); Class arguments[] = new Class[] {}; java.lang.reflect.Method objMethod = cl.getMethod(methodName, arguments); Object result = objMethod.invoke(invoker, (Object[]) arguments); System.out.println(result);//from ww w. j ava 2 s . c o m }
From source file:Main.java
public static void main(String[] argv) throws Exception { Class[] classParm = null;//from w ww . j av a 2s. c o m Object[] objectParm = null; try { String name = "java.lang.String"; Class cl = Class.forName(name); java.lang.reflect.Constructor co = cl.getConstructor(classParm); System.out.println(co.newInstance(objectParm)); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String args[]) throws Exception { Class cls = Class.forName("constructor2"); Class partypes[] = new Class[2]; partypes[0] = Integer.TYPE;//ww w .java 2 s . c o m partypes[1] = Integer.TYPE; Constructor ct = cls.getConstructor(partypes); Object arglist[] = new Object[2]; arglist[0] = new Integer(37); arglist[1] = new Integer(47); Object retobj = ct.newInstance(arglist); }
From source file:com.miraclelinux.historygluon.HistoryGluon.java
public static void main(String[] args) throws Exception { m_log = LogFactory.getLog(HistoryGluon.class); m_log.info("HistoryGluon, MIRACLE LINUX Corp. 2012"); if (!parseArgs(args)) return;/*from ww w. ja v a2s.co m*/ StorageDriver driver = null; String prefix = "com.miraclelinux.historygluon."; String driverName = prefix + m_storageName + "Driver"; try { Class<?> c = Class.forName(driverName); Class[] argTypes = { String[].class }; Constructor constructor = c.getConstructor(argTypes); Object[] driverArgs = { m_storageDriverArgs }; driver = (StorageDriver) constructor.newInstance(driverArgs); } catch (ClassNotFoundException e) { m_log.error("Unknown Storage Type: " + m_storageName); printUsage(); return; } catch (Exception e) { throw e; } if (!driver.init()) { m_log.fatal("Failed to initialize Storage Driver."); return; } m_log.info("StorageDriver: " + driver.getName()); if (m_isDeleteDBMode) { m_log.info("try to deleted DB..."); if (driver.deleteDB()) m_log.info("Success: Deleted DB"); else m_log.info("Failed: Deleted DB"); driver.close(); return; } ConnectionThread connectionThread = new ConnectionThread(DEFAULT_PORT, driver); connectionThread.start(); driver.close(); }
From source file:ArrayCreator.java
public static void main(String... args) { Matcher m = p.matcher(s);//from w w w . ja v a 2 s . co m if (m.find()) { String cName = m.group(1); String[] cVals = m.group(2).split("[\\s,]+"); int n = cVals.length; try { Class<?> c = Class.forName(cName); Object o = Array.newInstance(c, n); for (int i = 0; i < n; i++) { String v = cVals[i]; Constructor ctor = c.getConstructor(String.class); Object val = ctor.newInstance(v); Array.set(o, i, val); } Object[] oo = (Object[]) o; out.format("%s[] = %s%n", cName, Arrays.toString(oo)); // production code should handle these exceptions more gracefully } catch (ClassNotFoundException x) { x.printStackTrace(); } catch (NoSuchMethodException x) { x.printStackTrace(); } catch (IllegalAccessException x) { x.printStackTrace(); } catch (InstantiationException x) { x.printStackTrace(); } catch (InvocationTargetException x) { x.printStackTrace(); } } }
From source file:is.hi.bok.deduplicator.DigestIndexer.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) throws Exception { CommandLineParser clp = new CommandLineParser(args, new PrintWriter(System.out)); long start = System.currentTimeMillis(); // Set default values for all settings. boolean etag = false; boolean equivalent = false; boolean timestamp = false; String indexMode = MODE_BOTH; boolean addToIndex = false; String mimefilter = "^text/.*"; boolean blacklist = true; String iteratorClassName = CrawlLogIterator.class.getName(); String origin = null;/* www . j ava 2s . c o m*/ boolean skipDuplicates = false; // Process the options Option[] opts = clp.getCommandLineOptions(); for (int i = 0; i < opts.length; i++) { Option opt = opts[i]; switch (opt.getId()) { case 'w': blacklist = false; break; case 'a': addToIndex = true; break; case 'e': etag = true; break; case 'h': clp.usage(0); break; case 'i': iteratorClassName = opt.getValue(); break; case 'm': mimefilter = opt.getValue(); break; case 'o': indexMode = opt.getValue(); break; case 's': equivalent = true; break; case 't': timestamp = true; break; case 'r': origin = opt.getValue(); break; case 'd': skipDuplicates = true; break; default: System.err.println("Unhandled option id: " + opt.getId()); } } List cargs = clp.getCommandLineArguments(); if (cargs.size() != 2) { // Should be exactly two arguments. Source and target! clp.usage(0); } // Get the CrawlDataIterator // Get the iterator classname or load default. Class cl = Class.forName(iteratorClassName); Constructor co = cl.getConstructor(new Class[] { String.class }); CrawlDataIterator iterator = (CrawlDataIterator) co.newInstance(new Object[] { (String) cargs.get(0) }); // Print initial stuff System.out.println("Indexing: " + cargs.get(0)); System.out.println(" - Mode: " + indexMode); System.out.println(" - Mime filter: " + mimefilter + " (" + (blacklist ? "blacklist" : "whitelist") + ")"); System.out.println(" - Includes" + (equivalent ? " <equivalent URL>" : "") + (timestamp ? " <timestamp>" : "") + (etag ? " <etag>" : "")); System.out.println(" - Skip duplicates: " + (skipDuplicates ? "yes" : "no")); System.out.println(" - Iterator: " + iteratorClassName); System.out.println(" - " + iterator.getSourceType()); System.out.println("Target: " + cargs.get(1)); if (addToIndex) { System.out.println(" - Add to existing index (if any)"); } else { System.out.println(" - New index (erases any existing index at " + "that location)"); } DigestIndexer di = new DigestIndexer((String) cargs.get(1), indexMode, equivalent, timestamp, etag, addToIndex); // Create the index di.writeToIndex(iterator, mimefilter, blacklist, origin, true, skipDuplicates); // Clean-up di.close(); System.out.println("Total run time: " + ArchiveUtils.formatMillisecondsToConventional(System.currentTimeMillis() - start)); }
From source file:com.browseengine.bobo.index.MakeBobo.java
/** * @param args//ww w. j a va 2 s . co m */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Option help = new Option("help", false, "print this message"); OptionBuilder.withArgName("path"); OptionBuilder.hasArg(); OptionBuilder.withDescription("data source - required"); Option src = OptionBuilder.create("source"); src.setRequired(true); OptionBuilder.withArgName("path"); OptionBuilder.hasArg(); OptionBuilder.withDescription("index to create - required"); Option index = OptionBuilder.create("index"); index.setRequired(true); OptionBuilder.withArgName("file"); OptionBuilder.hasArg(); OptionBuilder.withDescription("field configuration - optional"); Option conf = OptionBuilder.create("conf"); OptionBuilder.withArgName("class"); OptionBuilder.hasArg(); OptionBuilder.withDescription("class name of the data digester - default: xml digester"); Option digesterOpt = OptionBuilder.create("digester"); OptionBuilder.withArgName("name"); OptionBuilder.hasArg(); OptionBuilder.withDescription("character set name - default: UTF-8"); Option charset = OptionBuilder.create("charset"); OptionBuilder.withArgName("maxdocs"); OptionBuilder.hasArg(); OptionBuilder.withDescription("maximum number of documents - default: 100"); Option maxdocs = OptionBuilder.create("maxdocs"); Options options = new Options(); options.addOption(help); options.addOption(conf); options.addOption(index); options.addOption(src); options.addOption(charset); options.addOption(digesterOpt); options.addOption(maxdocs); // create the parser CommandLineParser parser = new BasicParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); String output = line.getOptionValue("index"); File data = new File(line.getOptionValue("source")); Class digesterClass; if (line.hasOption("digester")) digesterClass = Class.forName(line.getOptionValue("digester")); else throw new RuntimeException("digester not specified"); Charset chset; if (line.hasOption("charset")) { chset = Charset.forName(line.getOptionValue("charset")); } else { chset = Charset.forName("UTF-8"); } int maxDocs; try { maxDocs = Integer.parseInt(line.getOptionValue("maxdocs")); } catch (Exception e) { maxDocs = 100; } FileDigester digester; try { Constructor constructor = digesterClass.getConstructor(new Class[] { File.class }); digester = (FileDigester) constructor.newInstance(new Object[] { data }); digester.setCharset(chset); digester.setMaxDocs(maxDocs); } catch (Exception e) { throw new RuntimeException("Invalid digester class.", e); } BoboIndexer indexer = new BoboIndexer(digester, FSDirectory.open(new File(output))); indexer.index(); } catch (ParseException exp) { exp.printStackTrace(); usage(options); } catch (ClassNotFoundException e) { System.out.println("Invalid digester class."); usage(options); } }
From source file:Cresendo.java
public static void main(String[] args) { String cfgFileReceiver = null; // Path to config file for eif receiver agent String cfgFileEngine = null; // Path to config file for xml event engine Options opts = null; // Command line options HelpFormatter hf = null; // Command line help formatter // Setup the message record which will contain text written to the log file ///*from www .j a v a 2s.c om*/ // The message logger object is created when the "-l" is processed // as this object need to be associated with a log file // LogRecord msg = new LogRecord(LogRecord.TYPE_INFO, "Cresendo", "main", "", "", "", "", ""); // Get the directory separator (defaults to "/") // dirSep = System.getProperty("file.separator", "/"); // Initialise the structure containing the event handler objects // Vector<IEventHandler> eventHandler = new Vector<IEventHandler>(10, 10); // Process the command line arguments // try { opts = new Options(); hf = new HelpFormatter(); opts.addOption("h", "help", false, "Command line arguments help"); opts.addOption("i", "instance name", true, "Name of cresendo instance"); opts.addOption("l", "log dir", true, "Path to log file directory"); opts.addOption("c", "config dir", true, "Path to configuarion file directory"); opts.getOption("l").setRequired(true); opts.getOption("c").setRequired(true); BasicParser parser = new BasicParser(); CommandLine cl = parser.parse(opts, args); // Print out some help and exit // if (cl.hasOption('h')) { hf.printHelp("Options", opts); System.exit(0); } // Set the instance name // if (cl.hasOption('i')) { instanceName = cl.getOptionValue('i'); // Set to something other than "default" } // Setup the message and trace logging objects for the EventEngine // if (cl.hasOption('l')) { // Setup the the paths to the message, trace and status log files // logDir = cl.getOptionValue("l"); logPath = logDir + dirSep + instanceName + "-engine.log"; tracePath = logDir + dirSep + instanceName + "-engine.trace"; statusPath = logDir + dirSep + instanceName + "-engine.status"; } else { // NOTE: This should be picked up by the MissingOptionException catch below // but I couldn't get this to work so I added the following code: // hf.printHelp("Option 'l' is a required option", opts); System.exit(1); } // Read the receiver and engine config files in the config directory // if (cl.hasOption('c')) { // Setup and check path to eif config file for TECAgent receiver object // configDir = cl.getOptionValue("c"); cfgFileReceiver = configDir + dirSep + instanceName + ".conf"; checkConfigFile(cfgFileReceiver); // Setup and check path to xml config file for the EventEngine // cfgFileEngine = cl.getOptionValue("c") + dirSep + instanceName + ".xml"; checkConfigFile(cfgFileEngine); } else { // NOTE: This should be picked up by the MissingOptionException catch below // but I couldn't get this to work so I added the following code: // hf.printHelp("Option 'c' is a required option", opts); System.exit(1); } } catch (UnrecognizedOptionException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (MissingOptionException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (MissingArgumentException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (ParseException e) { e.printStackTrace(); System.exit(1); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Main program // try { // ===================================================================== // Setup the message, trace and status logger objects // try { msgHandler = new FileHandler("cresendo", "message handler", logPath); msgHandler.openDevice(); msgLogger = new MessageLogger("cresendo", "message log"); msgLogger.addHandler(msgHandler); trcHandler = new FileHandler("cresendo", "trace handler", tracePath); trcHandler.openDevice(); trcLogger = new TraceLogger("cresendo", "trace log"); trcLogger.addHandler(trcHandler); statLogger = new StatusLogger(statusPath); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Add the shutdown hook // Runtime.getRuntime().addShutdownHook(new ShutdownThread(msgLogger, instanceName)); // --------------------------------------------------------------------- // ===================================================================== // Load and parse the xml event engine configuration file // // msg.setText("Loading xml engine from: '" + cfgFileEngine + "'"); try { XMLConfiguration xmlProcessor = new XMLConfiguration(); xmlProcessor.setFileName(cfgFileEngine); // Validate the xml against a document type declaration // xmlProcessor.setValidating(true); // Don't interpolate the tag contents by splitting them on a delimiter // (ie by default a comma) // xmlProcessor.setDelimiterParsingDisabled(true); // This will throw a ConfigurationException if the xml document does not // conform to its dtd. By doing this we hopefully catch any errors left // behind after the xml configuration file has been edited. // xmlProcessor.load(); // Setup the trace flag // ConfigurationNode engine = xmlProcessor.getRootNode(); List rootAttribute = engine.getAttributes(); for (Iterator it = rootAttribute.iterator(); it.hasNext();) { ConfigurationNode attr = (ConfigurationNode) it.next(); String attrName = attr.getName(); String attrValue = (String) attr.getValue(); if (attrValue == null || attrValue == "") { System.err.println("\n Error: The value of the attribute '" + attrName + "'" + "\n in the xml file '" + cfgFileEngine + "'" + "\n is not set"); System.exit(1); } if (attrName.matches("trace")) { if (attrValue.matches("true") || attrValue.matches("on")) { trcLogger.setLogging(true); } } if (attrName.matches("status")) { if (attrValue.matches("true") || attrValue.matches("on")) { statLogger.setLogging(true); } else { statLogger.setLogging(false); } } if (attrName.matches("interval")) { if (!attrValue.matches("[0-9]+")) { System.err.println("\n Error: The value of the interval attribute in: '" + cfgFileEngine + "'" + "\n should only contain digits from 0 to 9." + "\n It currently contains: '" + attrValue + "'"); System.exit(1); } statLogger.setInterval(Integer.parseInt(attrValue)); } } // Now build and instantiate the list of classes that will process events // received by the TECAgent receiver in a chain like manner. // List classes = xmlProcessor.configurationsAt("class"); for (Iterator it = classes.iterator(); it.hasNext();) { HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next(); // sub contains now all data contained in a single <class></class> tag set // String className = sub.getString("name"); // Log message // msg.setText(msg.getText() + "\n Instantiated event handler class: '" + className + "'"); // The angle brackets describing the class of object held by the // Vector are implemented by Java 1.5 and have 2 effects. // // 1. The list accepts only elements of that class and nothing else // (Of course thanks to Auto-Wrap you can also add double-values) // // 2. the get(), firstElement() ... Methods don't return a Object, but // they deliver an element of the class. // Vector<Class> optTypes = new Vector<Class>(10, 10); Vector<Object> optValues = new Vector<Object>(10, 10); for (int i = 0; i <= sub.getMaxIndex("option"); i++) { Object optValue = null; String optVarName = sub.getString("option(" + i + ")[@varname]"); String optJavaType = sub.getString("option(" + i + ")[@javatype]"); // Use the specified java type in order to make the method call // to the heirarchical sub object [painful :-((] // if (optJavaType.matches("byte")) { optTypes.addElement(byte.class); optValue = sub.getByte("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("short")) { optTypes.addElement(byte.class); optValue = sub.getShort("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("int")) { optTypes.addElement(int.class); optValue = sub.getInt("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("long")) { optTypes.addElement(long.class); optValue = sub.getLong("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("float")) { optTypes.addElement(float.class); optValue = sub.getFloat("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0.0; // Set to something nullish } } else if (optJavaType.matches("double")) { optTypes.addElement(double.class); optValue = sub.getDouble("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0.0; // Set to something nullish } } else if (optJavaType.matches("boolean")) { optTypes.addElement(boolean.class); optValue = sub.getBoolean("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = false; // Set to something nullish } } else if (optJavaType.matches("String")) { optTypes.addElement(String.class); optValue = sub.getString("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = ""; // Set it to something nullish } } else { System.err.println( "Error: Unsupported java type found in xml config: '" + optJavaType + "'"); System.exit(1); } // Add option value element // // System.out.println("Option value is: '" + optValue.toString() + "'\n"); // optValues.addElement(optValue); // Append to message text // String msgTemp = msg.getText(); msgTemp += "\n option name: '" + optVarName + "'"; msgTemp += "\n option type: '" + optJavaType + "'"; msgTemp += "\n option value: '" + optValues.lastElement().toString() + "'"; msg.setText(msgTemp); } try { // Instantiate the class with the java reflection api // Class klass = Class.forName(className); // Setup an array of paramater types in order to retrieve the matching constructor // Class[] types = optTypes.toArray(new Class[optTypes.size()]); // Get the constructor for the class which matches the parameter types // Constructor konstruct = klass.getConstructor(types); // Create an instance of the event handler // IEventHandler eventProcessor = (IEventHandler) konstruct.newInstance(optValues.toArray()); // Add the instance to the list of event handlers // eventHandler.addElement(eventProcessor); } catch (InvocationTargetException e) { System.err.println("Error: " + e.toString()); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: class name not found: '" + className + "' \n" + e.toString()); System.exit(1); } catch (Exception e) { System.err.println( "Error: failed to instantiate class: '" + className + "' \n" + e.toString()); System.exit(1); } } } catch (ConfigurationException cex) // Something went wrong loading the xml file { System.err.println("\n" + "Error loading XML file: " + cfgFileEngine + "\n" + cex.toString()); System.exit(1); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // --------------------------------------------------------------------- // ===================================================================== // Setup the TECAgent receiver // Reader cfgIn = null; try { cfgIn = new FileReader(cfgFileReceiver); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Start the TECAgent receiver and register the event engine handler // TECAgent receiver = new TECAgent(cfgIn, TECAgent.RECEIVER_MODE, false); EventEngine ee = new EventEngine(eventHandler, msgLogger, trcLogger); receiver.registerListener(ee); // Construct message and send it to the message log // String text = "\n Cresendo instance '" + instanceName + "' listening for events on port '" + receiver.getConfigVal("ServerPort") + "'"; msg.setText(msg.getText() + text); msgLogger.log(msg); // Send message to log // --------------------------------------------------------------------- // ===================================================================== // Initiate status logging // if (statLogger.isLogging()) { int seconds = statLogger.getInterval(); while (true) { try { statLogger.log(); } catch (Exception ex) { System.err.println("\n An error occurred while writing to '" + statusPath + "'" + "\n '" + ex.toString() + "'"); } Thread.sleep(seconds * 1000); // Convert sleep time to milliseconds } } // --------------------------------------------------------------------- } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } }
From source file:Main.java
private static <T> Collection<T> newCollection(Collection<T> coll) { try {/*w w w. j a va 2s. com*/ Class cl = coll.getClass(); Constructor con = cl.getConstructor(new Class[0]); return (Collection<T>) con.newInstance(new Object[0]); } catch (Exception e) { if (coll instanceof List) return new LinkedList<T>(); if (coll instanceof Set) return new HashSet<T>(); throw new RuntimeException("Cannot handle this collection"); } }