本文介绍了Java从DAO中删除重复的try,catch,最后的样板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DAO类,其中包含许多重复代码的方法: -

I have a DAO class with many methods that have a lot of repeated code along the lines of: -

public void method1(...) {
  Connection conn = null;
  try {
      //custom code here
  } catch (SQLException e) {
     LOG.error("Error accessing the database.", e);
     throw new DatabaseException();
  } catch (QueryNotFoundException e) {
     LOG.error("Error accessing the database.", e);
     throw new DatabaseException();
  } finally {
     if (conn != null)
        connectionPool.returnConnection(conn);
  } 

public void method2(...) {
  Connection conn = null;
  try {
      //different custom code here
  } catch (SQLException e) {
     LOG.error("Error accessing the database.", e);
     throw new DatabaseException();
  } catch (QueryNotFoundException e) {
     LOG.error("Error accessing the database.", e);
     throw new DatabaseException();
  } finally {
     if (conn != null)
        connectionPool.returnConnection(conn);
  } 

我想重组这个类,把try,catch,finally一个地方,以避免重复。我将如何实现这一目标?

I would like to restructure this class to put the try, catch, finally in one place to avoid repetation. How would I accomplish this?

推荐答案

为ex创建一个接口。可执行文件:

Create an interface for ex. Executable:

 public interface Executable() {

   void exec() throws SqlException();

 }

将每个dao方法重构为:

Refactor each of your dao method to :

public void method1() {
   execute(new Executable() {

     @Override
     public void exec() throws SqlException() {
          // your code here
     }
  });
  } 

在你的DAO中创建以下方法:

Create the following method execute in your DAO:

private void execute(Executor ex) {
    try {
      ex.exec();
    } catch(...) {
      ...
    } finally {
       ...
    }
}

这篇关于Java从DAO中删除重复的try,catch,最后的样板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 09:06