Does java have an equivalent to the C# “using” clause

后端 未结 12 1434
温柔的废话
温柔的废话 2020-12-29 23:09

I\'ve seen reference in some C# posted questions to a \"using\" clause. Does java have the equivalent?

12条回答
  •  误落风尘
    2020-12-29 23:25

    The closest you can get in Java is try/finally. Also, Java does not provide an implicit Disposable type.

    C#: scoping the variable outside a using block

    public class X : System.IDisposable {
    
        public void Dispose() {
            System.Console.WriteLine("dispose");
        }
    
        private static void Demo() {
            X x = new X();
            using(x) {
                int i = 1;
                i = i/0;
            }
        }
    
        public static void Main(System.String[] args) {
            try {
                Demo();
            } catch (System.DivideByZeroException) {}
        }
    
    }
    

    Java: scoping the variable outside a block

    public class X {
    
        public void dispose() {
            System.out.println("dispose");
        }
    
        private static void demo() {
            X x = new X();
            try {
                int i = 1 / 0;
            } finally {
                x.dispose();
            }        
        }
    
        public static void main(String[] args) {
            try {
                demo();
            } catch(ArithmeticException e) {}
        }
    
    }
    

    C#: scoping the variable inside a block

    public class X : System.IDisposable {
    
        public void Dispose() {
            System.Console.WriteLine("dispose");
        }
    
        private static void Demo() {
            using(X x = new X()) {
                int i = 1;
                i = i/0;
            }
        }
    
        public static void Main(System.String[] args) {
            try {
                Demo();
            } catch (System.DivideByZeroException) {}
        }
    
    }
    

    Java: scoping the variable inside a block

    public class X {
    
        public void dispose() {
            System.out.println("dispose");
        }
    
        private static void demo() {
            {
                X x = new X();
                try {
                    int i = 1 / 0;
                } finally {
                    x.dispose();
                }
            }
        }
    
        public static void main(String[] args) {
            try {
                demo();
            } catch(ArithmeticException e) {}
        }
    
    }
    

提交回复
热议问题