如何使用参数类型获取类

时间:2019-06-30 12:00:11

标签: kotlin mockito

我正在尝试获得Class>。

为了模拟观察者,我需要它是类。 我尝试使用Observer<Int>::class.java,但得到“类字面量的左侧仅允许类”

MWE(第1-2行是重要的,为完整起见,还包含域逻辑和模拟验证)

val clazz = Observer<Int>::class.java  // Error
val observer: Observer<Int> = mock(clazz)

addObserver(observer)
val y = 1
setObservedValue(y)


verify(observer).onChanged(y)

1 个答案:

答案 0 :(得分:0)

只有一个function solve(input) { let gender = (input.shift()); let age = Number(input.shift()); if (gender === 'Female') { if (age >= 18) { console.log('You are permitted on the website, lady.') } } else { console.log('You are not permitted on the website, lady.') } } else if (gender === 'Male') { if (age >= 18) { console.log('You are permitted on the website, dude.') } else { console.log('You are not permitted on the website, dude.') } } else { console.log('Error') } solve(['Female', '13']) ,它与type参数无关。所以你可以写

Observer::class

或者如果您不止一次遇到了这种情况(很可能)

@Suppress("UNCHECKED_CAST")
val clazz = Observer::class.java as Class<Observer<Int>>

称为

inline fun <reified T> mock(): T = mock(T::class.java)