这是Java代码:
public class TUtil {
public static <T> T getT(Object o, int i) {
try {
return ((Class<T>) ((ParameterizedType) (o.getClass()
.getGenericSuperclass())).getActualTypeArguments()[i])
.newInstance();
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (ClassCastException e) {
}
return null;
}
}
//use code:
public abstract class BaseMVPActivity<T extends BasePresenter, E extends BaseModel>{
···Omit code····
mPresenter = TUtil.getT(this, 0);
mModel = TUtil.getT(this, 1);
···Omit code····
}
我尝试用Kotlin编写以下uitl类:
class KClassUtil {
companion object {
inline fun <reified T> getKType(K: Any,position:Int):T {
var parameterizedType = K::class.java.genericSuperclass as ParameterizedType
var actualTypeArguments = parameterizedType.actualTypeArguments
return ( actualTypeArguments[position].javaClass as Class<T>).newInstance()
}
}
}
//use code:
abstract class BaseMVPActivity<T : BasePresenter<*, *>, E : BaseModel> : BaseActivity(){
···Omit code····
mPresenter = KClassUtil.getKType(this, 0) //error here
mModel = KClassUtil.getKType(this, 1) //error here
···Omit code····
}
错误提示是: 不能使用'T'作为化类型参数。请改用课程。
在这里,kotlin必须将我写给特定的类,但是由于这是一个抽象类,所以我不知道特定的类是什么。我该如何解决这个问题?