先上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;
}
}
//调用者只需要:
public abstract class BaseMVPActivity<T extends BasePresenter, E extends BaseModel>
···省略代码····
mPresenter = TUtil.getT(this, 0);
mModel = TUtil.getT(this, 1);
···省略代码····
我尝试使用kotlin去写这个util类:
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()
}
}
}
//调用者只需要:
abstract class BaseMVPActivity<T : BasePresenter<*, *>, E : BaseModel> : BaseActivity()
···省略代码····
mPresenter = KClassUtil.getKType(this, 0) //这里报错了
mModel = KClassUtil.getKType(this, 1) //这里报错了
···省略代码····
Cannot use 'T' as reified type parameter. Use a class instead.
这里kotlin中一定要我写入具体的Class,但由于这里是抽象类无法知道具体的class是什么,请问如何解决这个问题?
你无法获取这个泛型T的class,正确的获取方法应该是在BaseMVPActivity声明一个抽象的protected变量,由具体的activity去实现这个变量,比如
protected abstract val presenterClassToken: Class<T>
然后,在具体的activity继承这个BaseMVPActivity的时候,实现这个变量,XXXPresenter指具体的presenter实现类
class XXXXActivity(override val presenterClassToken: Class<XXXPresenter>)
以上,请参考