2017-09-14 80 views
0

出於調試的目的有我的代碼的一部分中,我要記錄一個方法的名稱,如:封裝在一個輔助方法獲取方法的名稱

val LOG = LogManager.getLogger(SomeClass::class.java.name) 
//... 
fun someMethod() { 
    LOG.debug(Thread.currentThread().getStackTrace()[1].getMethodName()) 

我怎麼能有這樣的作爲最小但清晰的表達?就像:

LOG.debug(getMethodName()) 

順便說一下,我嘗試使用AspectJ爲此,但我使用Eclipse和Kotlin插件與1.1.1一起使用。 AspectJ需要KAPT(據我所知),它不適用於1.1.1的maven(我也在使用它)。

回答

1

您可以定義在線程的擴展功能,讓你在棧上的第一種方法:

fun Thread.firstStackMethod() = stackTrace[1].methodName 

這樣稱呼它,那麼:

LOG.debug(Thread.currentThread().firstStackMethod()) 

也許它甚至有一個很好的選擇,爲你直接擴展記錄器:

fun Logger.debugMethodName(t: Thread) = debug(t.stackTrace[1].methodName) 
//use 
LOG.debugMethodName(Thread.currentThread()) 
2

您可以在文件級創建功能。

fun getMethodName(): String = 
    Thread.currentThread().stackTrace[1].methodName 

class Foo { 
    ... 
} 

通過調整stackTrace數字,您可以得到您想要的級別。