日期:2014-05-19  浏览次数:20635 次

求匿名内部类的正确使用方法,下面是一个查询数据库的方法。求解决问题。
Java code

            protected interface RestSet{
        public void close();
        public boolean next();
        public String getString(String s) throws SQLException;
        public String getString(int i) throws SQLException;
        public int count();
        }
            protected RestSet _select(final String sql){
        try {
            return new RestSet(){
                Statement __stt=__conn.createStatement();
                ResultSet __rs=__stt.executeQuery(sql);

                public void close(){
                    try{
                        if(__rs!=null){
                            __rs.close();
                        }
                        if(__stt!=null){
                            __stt.close();
                        }
                    } catch(SQLException e){
                        System.out.println("语句或结果集关闭失败");
                        e.printStackTrace();
                    }
                }

                public boolean next(){
                    try {
                        return __rs.next();
                    } catch (SQLException e) {
                        //不处理
                    }
                    return false;
                }
                
                public String getString(String s) throws SQLException{
                    return __rs.getString(s);
                }

                public String getString(int i) throws SQLException{
                    return __rs.getString(i);
                }
                
                public int count(){
                    try {
                        __rs.last();
                        int r=__rs.getRow();
                        __rs.beforeFirst();
                        return r;
                    } catch (SQLException e) {
                        //不处理
                    }
                    return 0;
                }
            };
        } catch (SQLException e) {
            System.out.println(sql);
            e.printStackTrace();
        } 
        return null;
    }



我写数据库操作的时候对于Statement和Resultset的释放比较头疼,想写一个这样的好用的方法。但是呢,调用close时貌似资源不释放啊,执行没有错误,在eclipse下debug提示求值期间出错,但是执行的时候没有异常,但是就是内存暴涨,求大牛们发表意见。

------解决方案--------------------
个人认为:不管是匿名还是不匿名,都系实例一个对象。对象中的属性已经实例化,但对象的方法是不会调用,必须由你调用。例如:
public int select(Reset rs){
int count = rs.count();
rs.close();
return cout;
}
调用时就可以使用匿名类:
实例select方法对应的类。
实例.select(
new Reset(){
对应方法的重写等等。
}
);