Tutorial :How to declare a global static class in Java?



Question:

In C# I am able to create a class like this:

static class clsDBUtils  {          public static SQLiteCommand cmd;          public static SQLiteConnection conn;          public static String databaseFilePath;            public static bool getConnection()          {          }  }  

Then anywhere in my namespace can use without initialization this way:

clsDBUtils.getConnection();  

How can this be rewritten for Java?

I don't want to use:

clsDBUtils sqlutil= new clsDBUtils();  


Solution:1

Basically the same way, just make a (normal) final class with a private contructor (prevents being able to do new) and add static members only.

public final class clsDBUtils {      public static SQLiteCommand cmd;      public static SQLiteConnection conn;      public static String databaseFilePath;        public static bool getConnection() {      }        private clsDBUtils() {}  }  


Solution:2

Apart from the particular question/problem, it is bad practice to declare expensive and external resources like Connection, Statement and ResultSet as an instance variable, let alone as a static variable. Those resources doesn't have an endless lifetime and your application may break when the DB decides to timeout the connection because it hasn't been released back to the DB after use.

I can't imagine that it's done differently in C# (it would have been a bug in the application as well), but the normal JDBC idiom is that you acquire and close it in the shortest possible scope, thus already inside the very same method block. E.g.

public Entity find(Long id) throws SQLException {      Connection connection = null;      PreparedStatement statement = null;      ResultSet resultSet = null;      Entity entity = null;        try {          connection = database.getConnection();          statement = connection.prepareStatement(SQL_FIND);          statement.setLong(1, id);          resultSet = statement.executeQuery();            if (resultSet.next()) {              entity = new Entity();              entity.setProperty(resultSet.getObject("columnname"));              // etc..          }      } finally {          // Always free resources in reversed order.          if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}          if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}          if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}      }        return entity;  }  

The database.getConnection() can however technically perfectly be made static like this:

public final class Database {      static {          try {              Class.forName("com.example.jdbc.Driver");          } catch (ClassNotFoundException e) {              throw new ExceptionInInitializerError(e);          }      }        private Database() {          // No need to instantiate this class.      }        public static Connection getConnection() {          DriverManager.getConnection("jdbc:example://localhost/dbname", "user", "pass");      }  }  

so that you can use it as

connection = Database.getConnection();  

(which you still really need to close in the finally block after use!)

However, this makes the connection source also really static. You cannot take benefit of polymorphism and/or inheritance anymore to switch between connection sources, such as a connection pool (to get better performance). To get more ideas/insights you may find this article useful


Solution:3

The code for it is almost exactly the same (same concept, slightly different syntax)

public class ClsDBUtils  {      public static SQLiteCommand cmd;      public static SQLiteConnection conn;      public static String databaseFilePath;        public static boolean getConnection()      {      }  }    // somewhere else  ClsDBUtils.getConnection();  


Solution:4

Just declare a public class and use the 'static' modifier on your methods and fields. If you do not want it to be instantiated, use 'public final class '. Alternatively, you can use a singleton class.


Solution:5

You want to implement the Singleton pattern: http://en.wikipedia.org/wiki/Singleton_pattern

public class clsDBUtils {     private static final clsDBUtils INSTANCE = new clsDBUtils();       // Private constructor prevents instantiation from other classes     private clsDBUtils() {}       public static clsDBUtils getInstance() {        return INSTANCE;     }       public SQLiteCommand cmd;     public SQLiteConnection conn;     public String databaseFilePath;       public bool getConnection()     {     }   }  

You can then use the following syntax on your class:

clsDBUtils.getInstance().getConnection();  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »