简体   繁体   English

如何重用java代码块

[英]How to reuse java code block

I want to reuse block of java code. 我想重用java代码块。

This is full code block: 这是完整的代码块:

    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();

        // begin of different part  
        Criteria criteria=session.createCriteria(Table.class);
        if(filters!=null)
            createFilter(criteria, filters, null,null);                 
        long count=(long)criteria.setProjection(Projections.rowCount()).uniqueResult();
        this.setRowCount((int) count);
        // end of different part

        session.getTransaction().commit();
    } catch (HibernateException e) {
        if(session.getTransaction()!=null)
            session.getTransaction().rollback();
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
}

And I need to use blocks: 我需要使用块:

    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();

and

        session.getTransaction().commit();
    } catch (HibernateException e) {
        if(session.getTransaction()!=null)
            session.getTransaction().rollback();
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
}

many times in different classes. 很多次在不同的班级。 But the middle part will be different. 但中间部分会有所不同。 Is there any way to do it? 有什么办法吗?

I'm going to make an example from a stripped down version of your code, so that it works without Hibernate. 我将从你的代码的精简版本中做一个例子,这样它就可以在没有Hibernate的情况下运行。

Original code: 原始代码:

public class MyClass {
    private int rowCount;

    public void doStuff() {
        Object session = new Object();

        try {
            session.getClass();  // represents session.getTransaction();

            // begin of different part
            String s = session.toString();
            System.out.println(s);
            this.setRowCount(5);
            // end of different part

            session.getClass();  // represents commit
        } catch (Exception e) {
            e.printStacktrace();
        } finally {
            System.out.println("Do some cleanup");
        }
    }

    public void setRowCount(int count) {
        rowCount = count;
    }
}

This would be called from some other place as: 这可以从其他地方调用:

MyCLass obj = new MyClass();
obj.doStuff();

Now for the changes. 现在进行更改。 I'm going to use lambda expressions plus define an interface with the annotation @FunctionalInterface . 我将使用lambda表达式并使用注释@FunctionalInterface定义一个interface This is because the apply method in the interface will return an Exception . 这是因为接口中的apply方法将返回Exception The standard functional interfaces in Java 8 don't support that. Java 8中的标准功能接口不支持它。

First the new interface: 首先是新界面:

@FunctionalInterface
public interface MyFunction {
    void apply(Object session, MyClass self) throws Exception;
}

Now the changes in the original code: 现在原始代码的变化:

change from 改变

    public void doStuff() {

to

    public void doStuff(MyFunction func) {

Remove the part labelled different code and replace it with: 删除标有不同代码的部分并将其替换为:

    func.apply(session, this);

And the calling from: 来自:

obj.doStuff();

to

obj.doStuff((session, self) -> {
    String s = session.toString();
    System.out.println(s);
    self.setRowCount(5);
});

If Java 8 is not an option, remove @FunctionalInterface in the interface. 如果Java 8不是选项,请在界面中删除@FunctionalInterface Then call doStuff() like this: 然后像这样调用doStuff()

obj.doStuff(new MyFunction() {
    @Override
    public void apply(Object session, MyClass self) throws Exception {
        String s = session.toString();
        System.out.println(s);
        self.setRowCount(5);
    }
});

The following is an example using Runnable as functional interface. 以下是使用Runnable作为功能接口的示例。 If you need to pass params, you could also write your own. 如果你需要传递params,你也可以自己编写。

To be clean, you could also write your own functional interface, because Runnable is normally used when it's about Threading. 为了保持干净,您还可以编写自己的功能界面,因为Runnable通常在涉及线程时使用。

public class RunnableExample {

    public static void main(String[] args) {
        RunnableExample example = new RunnableExample();
        example.general(() -> {
            System.out.println("specificA");
        });
        example.general(() -> {
            System.out.println("specificB");
        });
    }

    public void general(Runnable specific) {
        System.out.println("general start");
        specific.run();
        System.out.println("general end");
    }
}

Output: 输出:

general start
specificA
general end
general start
specificB
general end

Try using a helper class like this: 尝试使用这样的帮助程序类:

{
    Session session = null;
    try {
        session = DBHelper.getSession();

        // begin of different part  
        Criteria criteria=session.createCriteria(Table.class);
        if(filters!=null)
            createFilter(criteria, filters, null,null);                 
        long count=(long)criteria.setProjection(Projections.rowCount()).uniqueResult();
        this.setRowCount((int) count);
        // end of different part

        DBHelper.commit(session);
    } catch (HibernateException e) {
        DBHelper.rollback(session);
        e.printStackTrace();
    } finally {
        DBHelper.close(session);
    }
}

// Helper Class

class DBHelper{
    public static Session getSession() throws HibernateException{   
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        return session;
    }

    public static void rollback(Session session) throws HibernateException{
        if(session.getTransaction()!=null)
            session.getTransaction().rollback();
    }

    public static void commit(Session session) throws HibernateException{
        session.getTransaction().commit();
    }

    public static void close(Session session){
        if(session!=null){
            try{
                session.flush();
                session.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM