Example usage for java.lang Class forName

List of usage examples for java.lang Class forName

Introduction

In this page you can find the example usage for java.lang Class forName.

Prototype

@CallerSensitive
public static Class<?> forName(String className) throws ClassNotFoundException 

Source Link

Document

Returns the Class object associated with the class or interface with the given string name.

Usage

From source file:com.thoughtworks.xstream.benchmark.cache.CacheBenchmark.java

public static void main(String[] args) {
    int counter = 10000;
    Product product = null;//ww  w.  j a va2  s . co  m

    Options options = new Options();
    options.addOption("p", "product", true, "Class name of the product to use for benchmark");
    options.addOption("n", true, "Number of repetitions");

    Parser parser = new PosixParser();
    try {
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption('p')) {
            product = (Product) Class.forName(commandLine.getOptionValue('p')).newInstance();
        }
        if (commandLine.hasOption('n')) {
            counter = Integer.parseInt(commandLine.getOptionValue('n'));
        }
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    Harness harness = new Harness();
    // harness.addMetric(new SerializationSpeedMetric(1) {
    // public String toString() {
    // return "Initial run serialization";
    // }
    // });
    // harness.addMetric(new DeserializationSpeedMetric(1, false) {
    // public String toString() {
    // return "Initial run deserialization";
    // }
    // });
    harness.addMetric(new SerializationSpeedMetric(counter));
    harness.addMetric(new DeserializationSpeedMetric(counter, false));
    if (product == null) {
        harness.addProduct(new NoCache());
        harness.addProduct(new Cache122());
        harness.addProduct(new RealClassCache());
        harness.addProduct(new SerializedClassCache());
        harness.addProduct(new AliasedAttributeCache());
        harness.addProduct(new DefaultImplementationCache());
        harness.addProduct(new NoCache());
    } else {
        harness.addProduct(product);
    }
    harness.addTarget(new BasicTarget());
    harness.addTarget(new ExtendedTarget());
    harness.addTarget(new ReflectionTarget());
    harness.addTarget(new SerializableTarget());
    harness.run(new TextReporter(new PrintWriter(System.out, true)));
    System.out.println("Done.");
}

From source file:TypeConcurrency.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*from w  ww. j  a va  2 s.  c o  m*/
    Statement stmt;
    try {

        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {

        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        ResultSet srs = stmt.executeQuery("SELECT * FROM COFFEES");

        int type = srs.getType();

        System.out.println("srs is type " + type);

        int concur = srs.getConcurrency();

        System.out.println("srs has concurrency " + concur);
        while (srs.next()) {
            String name = srs.getString("COF_NAME");
            int id = srs.getInt("SUP_ID");
            float price = srs.getFloat("PRICE");
            int sales = srs.getInt("SALES");
            int total = srs.getInt("TOTAL");
            System.out.print(name + "   " + id + "   " + price);
            System.out.println("   " + sales + "   " + total);
        }

        srs.close();
        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("-----SQLException-----");
        System.err.println("SQLState:  " + ex.getSQLState());
        System.err.println("Message:  " + ex.getMessage());
        System.err.println("Vendor:  " + ex.getErrorCode());
    }
}

From source file:RSMetaDataMethods.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;//from   w  w  w  . j a  v a 2s.  c  o m
    Statement stmt;

    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();

        ResultSet rs = stmt.executeQuery("select * from COFFEES");
        ResultSetMetaData rsmd = rs.getMetaData();

        int numberOfColumns = rsmd.getColumnCount();
        for (int i = 1; i <= numberOfColumns; i++) {
            String colName = rsmd.getColumnName(i);
            String tableName = rsmd.getTableName(i);
            String name = rsmd.getColumnTypeName(i);
            boolean caseSen = rsmd.isCaseSensitive(i);
            boolean writable = rsmd.isWritable(i);
            System.out.println("Information for column " + colName);
            System.out.println("    Column is in table " + tableName);
            System.out.println("    DBMS name for type is " + name);
            System.out.println("    Is case sensitive:  " + caseSen);
            System.out.println("    Is possibly writable:  " + writable);
            System.out.println("");
        }

        while (rs.next()) {
            for (int i = 1; i <= numberOfColumns; i++) {
                String s = rs.getString(i);
                System.out.print(s + "  ");
            }
            System.out.println("");
        }

        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:TypeInfo.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;//  w  ww.j  a va 2  s. c  o m
    DatabaseMetaData dbmd;

    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        dbmd = con.getMetaData();

        ResultSet rs = dbmd.getTypeInfo();
        while (rs.next()) {
            String typeName = rs.getString("TYPE_NAME");
            short dataType = rs.getShort("DATA_TYPE");
            String createParams = rs.getString("CREATE_PARAMS");
            int nullable = rs.getInt("NULLABLE");
            boolean caseSensitive = rs.getBoolean("CASE_SENSITIVE");
            System.out.println("DBMS type " + typeName + ":");
            System.out.println("     java.sql.Types:  " + dataType);
            System.out.print("     parameters used to create: ");
            System.out.println(createParams);
            System.out.println("     nullable?:  " + nullable);
            System.out.print("     case sensitive?:  ");
            System.out.println(caseSensitive);
            System.out.println("");

        }

        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:InsertRows.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/* w ww  .ja v a 2 s . co m*/
    Statement stmt;
    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {

        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

        ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");

        uprs.moveToInsertRow();

        uprs.updateString("COF_NAME", "Kona");
        uprs.updateInt("SUP_ID", 150);
        uprs.updateFloat("PRICE", 10.99f);
        uprs.updateInt("SALES", 0);
        uprs.updateInt("TOTAL", 0);

        uprs.insertRow();

        uprs.updateString("COF_NAME", "Kona_Decaf");
        uprs.updateInt("SUP_ID", 150);
        uprs.updateFloat("PRICE", 11.99f);
        uprs.updateInt("SALES", 0);
        uprs.updateInt("TOTAL", 0);

        uprs.insertRow();

        uprs.beforeFirst();

        System.out.println("Table COFFEES after insertion:");
        while (uprs.next()) {
            String name = uprs.getString("COF_NAME");
            int id = uprs.getInt("SUP_ID");
            float price = uprs.getFloat("PRICE");
            int sales = uprs.getInt("SALES");
            int total = uprs.getInt("TOTAL");
            System.out.print(name + "   " + id + "   " + price);
            System.out.println("   " + sales + "   " + total);
        }

        uprs.close();
        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:SetSavepoint.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";

    try {//from w  w  w .ja v a 2 s .  c om

        Class.forName("myDriver.className");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {

        Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");
        con.setAutoCommit(false);

        String query = "SELECT COF_NAME, PRICE FROM COFFEES " + "WHERE TOTAL > ?";
        String update = "UPDATE COFFEES SET PRICE = ? " + "WHERE COF_NAME = ?";

        PreparedStatement getPrice = con.prepareStatement(query);
        PreparedStatement updatePrice = con.prepareStatement(update);

        getPrice.setInt(1, 7000);
        ResultSet rs = getPrice.executeQuery();

        Savepoint save1 = con.setSavepoint();

        while (rs.next()) {
            String cof = rs.getString("COF_NAME");
            float oldPrice = rs.getFloat("PRICE");
            float newPrice = oldPrice + (oldPrice * .05f);
            updatePrice.setFloat(1, newPrice);
            updatePrice.setString(2, cof);
            updatePrice.executeUpdate();
            System.out.println("New price of " + cof + " is " + newPrice);
            if (newPrice > 11.99) {
                con.rollback(save1);
            }

        }

        getPrice = con.prepareStatement(query);
        updatePrice = con.prepareStatement(update);

        getPrice.setInt(1, 8000);

        rs = getPrice.executeQuery();
        System.out.println();

        Savepoint save2 = con.setSavepoint();

        while (rs.next()) {
            String cof = rs.getString("COF_NAME");
            float oldPrice = rs.getFloat("PRICE");
            float newPrice = oldPrice + (oldPrice * .05f);
            updatePrice.setFloat(1, newPrice);
            updatePrice.setString(2, cof);
            updatePrice.executeUpdate();
            System.out.println("New price of " + cof + " is " + newPrice);
            if (newPrice > 11.99) {
                con.rollback(save2);
            }
        }

        con.commit();

        Statement stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT COF_NAME, " + "PRICE FROM COFFEES");

        System.out.println();
        while (rs.next()) {
            String name = rs.getString("COF_NAME");
            float price = rs.getFloat("PRICE");
            System.out.println("Current price of " + name + " is " + price);
        }

        con.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.l2jserver.model.template.SkillTemplateConverter.java

public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException {
    Class.forName("com.mysql.jdbc.Driver");

    final File target = new File("data/templates");
    final JAXBContext c = JAXBContext.newInstance(SkillTemplate.class, LegacySkillList.class);
    final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);

    System.out.println("Generating template XML files...");
    c.generateSchema(new SchemaOutputResolver() {
        @Override/*  w w  w  . j  a v  a  2s  .  com*/
        public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
            return new StreamResult(new File(target, suggestedFileName));
        }
    });

    try {
        final Unmarshaller u = c.createUnmarshaller();
        final Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "skill");
        m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "skill ../skill.xsd");

        Collection<File> files = FileUtils.listFiles(new File(LEGACY_SKILL_FOLDER), new String[] { "xml" },
                true);
        for (final File legacyFile : files) {
            LegacySkillList list = (LegacySkillList) u.unmarshal(legacyFile);
            for (final LegacySkill legacySkill : list.skills) {
                SkillTemplate t = fillSkill(legacySkill);
                final File file = new File(target, "skill/" + t.id.getID()
                        + (t.getName() != null ? "-" + camelCase(t.getName()) : "") + ".xml");
                templates.add(t);

                try {
                    m.marshal(t, getXMLSerializer(new FileOutputStream(file)));
                } catch (MarshalException e) {
                    System.err.println(
                            "Could not generate XML template file for " + t.getName() + " - " + t.getID());
                    file.delete();
                }
            }
        }

        System.out.println("Generated " + templates.size() + " templates");

        System.gc();
        System.out.println("Free: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory()));
        System.out.println("Total: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory()));
        System.out.println("Used: " + FileUtils.byteCountToDisplaySize(
                Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
        System.out.println("Max: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory()));
    } finally {
        conn.close();
    }
}

From source file:CreateRef.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con;/*from w  w w .j  a  v a  2  s . com*/
    Statement stmt;
    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        String createManagers = "CREATE TABLE MANAGERS OF MANAGER "
                + "(OID REF(MANAGER) VALUES ARE SYSTEM GENERATED)";

        String insertManager1 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES "
                + "(000001, 'MONTOYA', 'ALFREDO', '8317225600')";

        String insertManager2 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES "
                + "(000002, 'HASKINS', 'MARGARET', '4084355600')";

        String insertManager3 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES "
                + "(000003, 'CHEN', 'HELEN', '4153785600')";

        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();
        stmt.executeUpdate(createManagers);

        con.setAutoCommit(false);

        stmt.addBatch(insertManager1);
        stmt.addBatch(insertManager2);
        stmt.addBatch(insertManager3);
        int[] updateCounts = stmt.executeBatch();

        con.commit();

        System.out.println("Update count for:  ");
        for (int i = 0; i < updateCounts.length; i++) {
            System.out.print("    command " + (i + 1) + " = ");
            System.out.println(updateCounts[i]);
        }

        stmt.close();
        con.close();

    } catch (BatchUpdateException b) {
        System.err.println("-----BatchUpdateException-----");
        System.err.println("Message:  " + b.getMessage());
        System.err.println("SQLState:  " + b.getSQLState());
        System.err.println("Vendor:  " + b.getErrorCode());
        System.err.print("Update counts for successful commands:  ");
        int[] rowsUpdated = b.getUpdateCounts();
        for (int i = 0; i < rowsUpdated.length; i++) {
            System.err.print(rowsUpdated[i] + "   ");
        }
        System.err.println("");
    } catch (SQLException ex) {
        System.err.println("------SQLException------");
        System.err.println("Error message:  " + ex.getMessage());
        System.err.println("SQLState:  " + ex.getSQLState());
        System.err.println("Vendor:  " + ex.getErrorCode());
    }
}

From source file:InsertCoffees.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/* ww  w  .  j  av  a  2  s. c o  m*/
    Statement stmt;
    String query = "select COF_NAME, PRICE from COFFEES";

    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {

        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();

        stmt.executeUpdate("insert into COFFEES " + "values('Colombian', 00101, 7.99, 0, 0)");

        stmt.executeUpdate("insert into COFFEES " + "values('French_Roast', 00049, 8.99, 0, 0)");

        stmt.executeUpdate("insert into COFFEES " + "values('Espresso', 00150, 9.99, 0, 0)");

        stmt.executeUpdate("insert into COFFEES " + "values('Colombian_Decaf', 00101, 8.99, 0, 0)");

        stmt.executeUpdate("insert into COFFEES " + "values('French_Roast_Decaf', 00049, 9.99, 0, 0)");

        ResultSet rs = stmt.executeQuery(query);

        System.out.println("Coffee Break Coffees and Prices:");
        while (rs.next()) {
            String s = rs.getString("COF_NAME");
            float f = rs.getFloat("PRICE");
            System.out.println(s + "   " + f);
        }

        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:InsertSuppliers.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;//www. j a va  2s .  c  om
    Statement stmt;
    String query = "select SUP_NAME, SUP_ID from SUPPLIERS";

    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();

        stmt.executeUpdate("insert into SUPPLIERS " + "values(49, 'Superior Coffee', '1 Party Place', "
                + "'Mendocino', 'CA', '95460')");

        stmt.executeUpdate("insert into SUPPLIERS " + "values(101, 'Acme, Inc.', '99 Market Street', "
                + "'Groundsville', 'CA', '95199')");

        stmt.executeUpdate("insert into SUPPLIERS " + "values(150, 'The High Ground', '100 Coffee Lane', "
                + "'Meadows', 'CA', '93966')");

        ResultSet rs = stmt.executeQuery(query);

        System.out.println("Suppliers and their ID Numbers:");
        while (rs.next()) {
            String s = rs.getString("SUP_NAME");
            int n = rs.getInt("SUP_ID");
            System.out.println(s + "   " + n);
        }

        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}