2017-10-10 29 views
0

我想爲類名稱間距原因在Foo類中定義BarException。這是我的Foo類的樣子:由於未找到構造函數而無法實例化嵌套的異常類

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)

我曾嘗試使用new BarException(this, r)實例化BarException,並將groovy.transform.InheritConstructors放在BarException左右,但對編譯器無效。

有什麼問題?

回答

0

嘗試使BarException爲靜態並添加@InheritConstructors

import groovy.transform.InheritConstructors 

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

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

groovy docs

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操作系統:Mac OS X' –

相關問題