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:HasBatteries.java

public static void main(String[] args) {
    Class c = null;// ww  w .  java 2  s.c  o m
    try {
        c = Class.forName("FancyToy");
    } catch (ClassNotFoundException e) {
        System.out.println("Can't find FancyToy");
        System.exit(1);
    }
    printInfo(c);
    Class[] faces = c.getInterfaces();
    for (int i = 0; i < faces.length; i++)
        printInfo(faces[i]);
    Class cy = c.getSuperclass();
    Object o = null;
    try {
        // Requires default constructor:
        o = cy.newInstance(); // (*1*)
    } catch (InstantiationException e) {
        System.out.println("Cannot instantiate");
        System.exit(1);
    } catch (IllegalAccessException e) {
        System.out.println("Cannot access");
        System.exit(1);
    }
    printInfo(o.getClass());

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;

    String createTableSQL = "CREATE TABLE Person(" + "USER_ID NUMBER(5) NOT NULL, "
            + "USERNAME VARCHAR(20) NOT NULL, " + "CREATED_BY VARCHAR(20) NOT NULL, "
            + "CREATED_DATE DATE NOT NULL, " + "PRIMARY KEY (USER_ID) " + ")";

    Class.forName(DB_DRIVER);
    dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);

    preparedStatement = dbConnection.prepareStatement(createTableSQL);

    System.out.println(createTableSQL);

    preparedStatement.executeUpdate();//from  w w w .j  av a  2s  .c om

    preparedStatement.close();
    dbConnection.close();

}

From source file:CompileString.java

public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    String program = "class Test{" + "   public static void main (String [] args){"
            + "      System.out.println (\"Hello, World\");" + "      System.out.println (args.length);"
            + "   }" + "}";

    Iterable<? extends JavaFileObject> fileObjects;
    fileObjects = getJavaSourceFromString(program);

    compiler.getTask(null, null, null, null, null, fileObjects).call();

    Class<?> clazz = Class.forName("Test");
    Method m = clazz.getMethod("main", new Class[] { String[].class });
    Object[] _args = new Object[] { new String[0] };
    m.invoke(null, _args);/*w w w .  j av a2  s.  c o m*/
}

From source file:History.PieChart_DB.java

public static void main(String[] args) throws Exception {

    String mobilebrands[] = { "IPhone 5s", "SamSung Grand", "MotoG", "Nokia Lumia" };
    int statOfRepair = 0;
    java.util.Date now = new java.util.Date();
    String adminDate = (now.getYear() + 1900) + "-" + (now.getMonth() + 1) + "-" + now.getDate();
    /* Create MySQL Database Connection */
    Class.forName("com.mysql.jdbc.Driver");
    Connection connect = ConnectDatabase.connectDb("win", "win016");

    Statement statement = connect.createStatement();
    ResultSet resultSet = statement
            .executeQuery("SELECT COUNT(transID) AS statRepair FROM `Transaction` WHERE dateTime LIKE \'"
                    + adminDate + "%\' AND action LIKE 'Repair'");
    DefaultPieDataset dataset = new DefaultPieDataset();

    while (resultSet.next()) {
        dataset.setValue(resultSet.getString("statRepair"),
                Double.parseDouble(resultSet.getString("unit_sale")));
    }//  ww  w . j a  v  a2s.c  o  m

    JFreeChart chart = ChartFactory.createPieChart("History", // chart title           
            dataset, // data           
            true, // include legend          
            true, false);

    int width = 560; /* Width of the image */
    int height = 370; /* Height of the image */
    File pieChart = new File("Pie_Chart.jpeg");
    ChartUtilities.saveChartAsJPEG(pieChart, chart, width, height);
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element results = doc.createElement("Results");
    doc.appendChild(results);//from w  w  w.j  a  va2s  .c om

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager
            .getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/access.mdb");

    ResultSet rs = con.createStatement().executeQuery("select * from product");

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);
        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);
        }
    }
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);

    System.out.println(sw.toString());

    con.close();
    rs.close();
}

From source file:ShowMethods.java

public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println(usage);
        System.exit(0);//from  w ww .  java 2  s. c  o m
    }
    int lines = 0;
    try {
        Class c = Class.forName(args[0]);
        Method[] m = c.getMethods();
        Constructor[] ctor = c.getConstructors();
        if (args.length == 1) {
            for (int i = 0; i < m.length; i++)
                System.out.println(p.matcher(m[i].toString()).replaceAll(""));
            for (int i = 0; i < ctor.length; i++)
                System.out.println(p.matcher(ctor[i].toString()).replaceAll(""));
            lines = m.length + ctor.length;
        } else {
            for (int i = 0; i < m.length; i++)
                if (m[i].toString().indexOf(args[1]) != -1) {
                    System.out.println(p.matcher(m[i].toString()).replaceAll(""));
                    lines++;
                }
            for (int i = 0; i < ctor.length; i++)
                if (ctor[i].toString().indexOf(args[1]) != -1) {
                    System.out.println(p.matcher(ctor[i].toString()).replaceAll(""));
                    lines++;
                }
        }
    } catch (ClassNotFoundException e) {
        System.out.println("No such class: " + e);
    }
}

From source file:oobbit.Application.java

public static void main(String[] args) {
    try {/*w w  w . ja v  a 2  s.  co  m*/
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException ex) {
        System.out.println("You are missing the JDBC Driver (com.mysql.jdbc.Driver) "
                + "which is essential for this software to work. "
                + "Please make sure it's included pom.xml of this software.");
        System.exit(1); // Force quit (TODO?)
    }

    SpringApplication.run(Application.class, args);
}

From source file:ShowClass.java

/** The main method. Print info about the named class */
public static void main(String[] args) throws ClassNotFoundException {
    Class c = Class.forName(args[0]);
    print_class(c);
}

From source file:InsertCustomType2_Oracle.java

public static void main(String[] args) {
    String id = "001";
    String isbn = "1234567890";
    String title = "Java Oracle";
    String author = "java2s";
    int edition = 1;

    // create the Book object
    Book book = new Book(isbn, title, author, edition);
    book.print();/*from w w  w . ja  v a  2 s . c  o m*/

    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
        conn = getConnection();
        // create type map
        java.util.Map map = conn.getTypeMap();
        System.out.println("map=" + map);
        map.put("BOOK", Class.forName("Book"));
        System.out.println("map=" + map);

        String insert = "insert into book_table(ID, BOOK) values(?, ?)";
        pstmt = conn.prepareStatement(insert);
        pstmt.setString(1, id);
        pstmt.setObject(2, book);
        pstmt.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        try {
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.ninjacat.stubborn.Stubborn.java

public static void main(String[] argv) throws ClassNotFoundException, ParseException {
    Options options = createOptions();/*ww  w.  j  ava  2s.  c o m*/
    if (argv.length == 0) {
        printHelp(options);
        return;
    }

    Class.forName(Bootstrapper.class.getCanonicalName());
    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, argv);
        if (commandLine.hasOption("h")) {
            printHelp(options);
            return;
        }

        Context context = new Context(commandLine);

        Transformer transformer = Bootstrapper.get(Transformer.class);

        transformer.transform(context);
    } catch (MissingOptionException ex) {
        System.out.println("Missing required parameter " + ex.getMissingOptions());
        printHelp(options);
    } catch (TransformationException ex) {
        System.out.println("Failed to perform transformation caused by " + ex.getCause());
        System.out.println(ex.getMessage());
    }
}