2017-10-10 4 views
0

名前空間の理由でFooクラス内にBarExceptionを定義したいとします。コンストラクタが見つからないため、ネストされた例外クラスをインスタンス化できません。

package org.company.utils 

class Foo {                                
    class BarException extends RuntimeException { } 

    def raise() {                                
     def r = new RuntimeException("BOOM")                          
     throw new BarException(r) 
    } 
} 

これは私が仕事にそれを好きだろうかです::

void testFoo() { 
    shouldFail(Foo.BarException) { 
     def foo = new Foo() 
     foo.raise() 
    } 
    } 

しかし、テストが失敗しました:

1) testFoo(test.FooTestCase)java.lang.AssertionError: Closure [email protected] should have failed with an exception of type org.company.utils.Foo$BarException, instead got Exception groovy.lang.GroovyRuntimeException: Could not find matching constructor for: org.company.utils.Foo$BarException(org.company.utils.Foo, java.lang.RuntimeException)

私が試してみましたこれは私のFooクラスは次のようになりますnew BarException(this, r)を使用してBarExceptionをインスタンス化し、を約BarExceptionに置き換えますが、コンパイラでは何も機能しません。

問題が何ですか?

答えて

0

BarExceptionを静的にして、@InheritConstructorsを追加してみてください。 groovy docsから

import groovy.transform.InheritConstructors 

class Foo { 
    @InheritConstructors 
    static class BarException extends Exception { } 

    def raise() { 
     Throwable r = new RuntimeException("BOOM") 
     throw new BarException(r) 
    } 
} 

The usage of static inner classes is the best supported one. If you absolutely need an inner class, you should make it a static one.

+0

感謝。あなたの答えは私の問題に対処しましたが、可能であれば、なぜ私の考えが機能しないのかを「静的​​ではない」理由について説明したいと思います。 –

+0

使用しているGroovyのバージョンは? –

+0

'Groovyバージョン:2.4.11 JVM:1.8.0_144ベンダー:Oracle Corporation OS:Mac OS X' –

関連する問題