Share

Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#Class.forName' - 3 code snippet(s) found

 Sample 1. Database Api using java.sql classes

package BuggyBread;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseAPI {

   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "";

   // Database credentials
   static final String USER = "";
   static final String PASS = "";

   Connection conn = null;
   
   public void initializeConnection(){
      try {
         // STEP 2: Register JDBC driver
         Class.forName("com.mysql.jdbc.Driver");

         // STEP 3: Open a connection
         System.out.println("Connecting to database...");
         conn = DriverManager.getConnection(DB_URL, USER, PASS);

         conn.close();
      } catch (SQLException se) {
         // Handle errors for JDBC
         se.printStackTrace();
      } catch (Exception e) {
         // Handle errors for Class.forName
         e.printStackTrace();
      } finally {
         
         try {
            if (conn != null)
               conn.close();
         } catch (SQLException se) {
            se.printStackTrace();
         }// end finally try
      }// end try
   
   }
}

   Like      Feedback     database api  java.sql


 Sample 2. Loading Class using Class.forName ( Reflection )

Class clazz = null;
try {
   clazz = Class.forName("sun.awt.windows.WEmbeddedFrame");
} catch (Throwable e) {
}

Constructor constructor = null;
try {
   constructor = clazz.getConstructor(new Class[] { Integer.TYPE });
} catch (Throwable localThrowable1) {
}

   Like      Feedback     Class.forName  Reflection


 Sample 3. Code Sample / Example / Snippet of java.util.EventListener

    private void readObject(ObjectInputStream s)

throws IOException, ClassNotFoundException {

listenerList = NULL_ARRAY;

s.defaultReadObject();

Object listenerTypeOrNull;



while (null != (listenerTypeOrNull = s.readObject())) {

ClassLoader cl = Thread.currentThread().getContextClassLoader();

EventListener l = (EventListener)s.readObject();

String name = (String) listenerTypeOrNull;

ReflectUtil.checkPackageAccess(name);

add((Class<EventListener>)Class.forName(name, true, cl), l);

}

}




   Like      Feedback      java.util.EventListener



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner



comments powered by Disqus