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:io.apiman.tools.jdbc.ApimanJdbcServer.java

public static void main(String[] args) {
    try {/*from  w w  w  .j a v  a 2s  .com*/
        File dataDir = new File("target/h2");
        String url = "jdbc:h2:tcp://localhost:9092/apiman";

        if (dataDir.exists()) {
            FileUtils.deleteDirectory(dataDir);
        }
        dataDir.mkdirs();

        Server.createTcpServer("-tcpPassword", "sa", "-baseDir", dataDir.getAbsolutePath(), "-tcpPort", "9092",
                "-tcpAllowOthers").start();
        Class.forName("org.h2.Driver");

        try (Connection connection = DriverManager.getConnection(url, "sa", "")) {
            System.out.println("Connection Established: " + connection.getMetaData().getDatabaseProductName()
                    + "/" + connection.getCatalog());
            executeUpdate(connection,
                    "CREATE TABLE users ( username varchar(255) NOT NULL, password varchar(255) NOT NULL, PRIMARY KEY (username))");
            executeUpdate(connection,
                    "INSERT INTO users (username, password) VALUES ('bwayne', 'ae2efd698aefdf366736a4eda1bc5241f9fbfec7')");
            executeUpdate(connection,
                    "INSERT INTO users (username, password) VALUES ('ckent', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')");
            executeUpdate(connection,
                    "INSERT INTO users (username, password) VALUES ('ballen', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')");
            executeUpdate(connection,
                    "CREATE TABLE roles (rolename varchar(255) NOT NULL, username varchar(255) NOT NULL)");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('user', 'bwayne')");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('admin', 'bwayne')");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('ckent', 'user')");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('ballen', 'user')");
        }

        System.out.println("======================================================");
        System.out.println("JDBC (H2) server started successfully.");
        System.out.println("");
        System.out.println("  Data: " + dataDir.getAbsolutePath());
        System.out.println("  JDBC URL: " + url);
        System.out.println("  JDBC User: sa");
        System.out.println("  JDBC Password: ");
        System.out.println(
                "  Authentication Query:   SELECT * FROM users u WHERE u.username = ? AND u.password = ?");
        System.out.println("  Authorization Query:    SELECT r.rolename FROM roles r WHERE r.username = ?");
        System.out.println("======================================================");
        System.out.println("");
        System.out.println("");
        System.out.println("Press Enter to stop the JDBC server.");
        new BufferedReader(new InputStreamReader(System.in)).readLine();

        System.out.println("Shutting down the JDBC server...");

        Server.shutdownTcpServer("tcp://localhost:9092", "", true, true);

        System.out.println("Done!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:javasnack.cli.CliDbUnitCsvExportDemo.java

public static void main(String[] args) throws Exception {
    String driver = System.getProperty("CliDbUnitCsvExportDemo.driver", "org.h2.Driver");
    Class.forName(driver);
    String url = System.getProperty("CliDbUnitCsvExportDemo.url", "jdbc:h2:mem:CliDbUnitCsvExportDemo");
    String dbUser = System.getProperty("CliDbUnitCsvExportDemo.dbUser", "sa");
    String dbPassword = System.getProperty("CliDbUnitCsvExportDemo.dbPassword", "");
    Connection conn = DriverManager.getConnection(url, dbUser, dbPassword);

    CliDbUnitCsvExportDemo demo = new CliDbUnitCsvExportDemo();
    demo.setup(conn);/*www . java 2  s .  c  om*/

    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
    Calendar c = Calendar.getInstance();
    File outDir = new File(sdf1.format(c.getTime()));
    outDir.mkdir();

    IDatabaseConnection dbunit_conn = new DatabaseConnection(conn);
    IDataSet dataSet = dbunit_conn.createDataSet();

    CsvBase64BinarySafeDataSetWriter.write(dataSet, outDir);

    conn.close();
}

From source file:GenericReflectionTest.java

public static void main(String[] args) {
    // read class name from command line args or user input
    String name;//from   ww  w.ja  va 2 s.  com
    if (args.length > 0)
        name = args[0];
    else {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter class name (e.g. java.util.Collections): ");
        name = in.next();
    }

    try {
        // print generic info for class and public methods
        Class<?> cl = Class.forName(name);
        printClass(cl);
        for (Method m : cl.getDeclaredMethods())
            printMethod(m);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:Cls.java

public static void main(String... args) {
    try {//from w  w w .ja  v  a  2 s.co m
        Class<?> c = Class.forName("Cls");
        c.newInstance(); // InstantiationException

        // production code should handle these exceptions more gracefully
    } catch (InstantiationException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}

From source file:ConstructorTrouble.java

public static void main(String... args) {
    try {//from w w  w . ja v  a2 s.  co  m
        Class<?> c = Class.forName("ConstructorTrouble");
        Object o = c.newInstance(); // InstantiationException

        // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    } catch (InstantiationException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    }
}

From source file:org.eclipse.swt.snippets.SnippetLauncher.java

public static void main(String[] args) {
    File sourceDir = SnippetsConfig.SNIPPETS_SOURCE_DIR;
    boolean hasSource = sourceDir.exists();
    int count = 500;
    if (hasSource) {
        File[] files = sourceDir.listFiles();
        if (files.length > 0)
            count = files.length;/*from ww w  .  j  ava  2s  .  co m*/
    }
    for (int i = 1; i < count; i++) {
        if (SnippetsConfig.isPrintingSnippet(i))
            continue; // avoid printing to printer
        String className = "Snippet" + i;
        Class<?> clazz = null;
        try {
            clazz = Class.forName(SnippetsConfig.SNIPPETS_PACKAGE + "." + className);
        } catch (ClassNotFoundException e) {
        }
        if (clazz != null) {
            System.out.println("\n" + clazz.getName());
            if (hasSource) {
                File sourceFile = new File(sourceDir, className + ".java");
                try (FileReader reader = new FileReader(sourceFile);) {
                    char[] buffer = new char[(int) sourceFile.length()];
                    reader.read(buffer);
                    String source = String.valueOf(buffer);
                    int start = source.indexOf("package");
                    start = source.indexOf("/*", start);
                    int end = source.indexOf("* For a list of all");
                    System.out.println(source.substring(start, end - 3));
                    boolean skip = false;
                    String platform = SWT.getPlatform();
                    if (source.contains("PocketPC")) {
                        platform = "PocketPC";
                        skip = true;
                    } else if (source.contains("OpenGL")) {
                        platform = "OpenGL";
                        skip = true;
                    } else if (source.contains("JavaXPCOM")) {
                        platform = "JavaXPCOM";
                        skip = true;
                    } else {
                        String[] platforms = { "win32", "gtk" };
                        for (int p = 0; p < platforms.length; p++) {
                            if (!platforms[p].equals(platform) && source.contains("." + platforms[p])) {
                                platform = platforms[p];
                                skip = true;
                                break;
                            }
                        }
                    }
                    if (skip) {
                        System.out.println("...skipping " + platform + " example...");
                        continue;
                    }
                } catch (Exception e) {
                }
            }
            Method method = null;
            String[] param = SnippetsConfig.getSnippetArguments(i);
            try {
                method = clazz.getMethod("main", param.getClass());
            } catch (NoSuchMethodException e) {
                System.out.println("   Did not find main(String [])");
            }
            if (method != null) {
                try {
                    method.invoke(clazz, new Object[] { param });
                } catch (IllegalAccessException e) {
                    System.out.println("   Failed to launch (illegal access)");
                } catch (IllegalArgumentException e) {
                    System.out.println("   Failed to launch (illegal argument to main)");
                } catch (InvocationTargetException e) {
                    System.out.println("   Exception in Snippet: " + e.getTargetException());
                }
            }
        }
    }
}

From source file:InheritedMethods.java

public static void main(String... args) {
    try {//www. j  a va 2  s.  c  o  m
        Class<?> c = Class.forName(args[0]);
        printMethods(c);

        Class parent = c.getSuperclass();
        while (parent != null) {
            printMethods(parent);
            parent = parent.getSuperclass();
        }

        // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.dao.ExtractDataSetForCommonDBUnit.java

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

    Connection jdbcConnection = null;
    FileOutputStream fileOutputStream = null;

    try {/*  ww  w.j  a  v a2  s  .c  om*/
        // database connection
        Class.forName("org.postgresql.Driver");
        jdbcConnection = DriverManager.getConnection(DBURL, DBUser, DBPass);

        final IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);

        ITableFilter filter = new DatabaseSequenceFilter(connection);
        DatabaseConfig config = connection.getConfig();
        config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new PostgresqlDataTypeFactory());

        QueryDataSet ds = new QueryDataSet(connection, true);

        ds.addTable("log");

        String outputPath = DB_DUMP_FOLDER + DB_DUMP_FILE;
        //noinspection IOResourceOpenedButNotSafelyClosed
        fileOutputStream = new FileOutputStream(outputPath);
        FlatXmlDataSet.write(ds, fileOutputStream);
    } finally {
        if (jdbcConnection != null) {
            jdbcConnection.close();
        }

        IOUtils.closeQuietly(fileOutputStream);
    }
}

From source file:ArrayFind.java

public static void main(String... args) {
    boolean found = false;
    try {/*  ww w .  jav  a2s  .c o m*/
        Class<?> cls = Class.forName(args[0]);
        Field[] flds = cls.getDeclaredFields();
        for (Field f : flds) {
            Class<?> c = f.getType();
            if (c.isArray()) {
                found = true;
                out.format(
                        "%s%n" + "           Field: %s%n" + "            Type: %s%n" + "  Component Type: %s%n",
                        f, f.getName(), c, c.getComponentType());
            }
        }
        if (!found) {
            out.format("No array fields%n");
        }

        // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}

From source file:ConstructorSift.java

public static void main(String... args) {
    try {// w  w  w  .  ja v a2 s  .  c o m
        Class<?> cArg = Class.forName(args[1]);

        Class<?> c = Class.forName(args[0]);
        Constructor[] allConstructors = c.getDeclaredConstructors();
        for (Constructor ctor : allConstructors) {
            Class<?>[] pType = ctor.getParameterTypes();
            for (int i = 0; i < pType.length; i++) {
                if (pType[i].equals(cArg)) {
                    out.format("%s%n", ctor.toGenericString());

                    Type[] gpType = ctor.getGenericParameterTypes();
                    for (int j = 0; j < gpType.length; j++) {
                        char ch = (pType[j].equals(cArg) ? '*' : ' ');
                        out.format("%7c%s[%d]: %s%n", ch, "GenericParameterType", j, gpType[j]);
                    }
                    break;
                }
            }
        }

        // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}