admin管理员组文章数量:1122832
Let's say I have this class:
class GenericClass<T>(
private val param1: String = ""
private val param2: ((String, String) -> Unit)? = null
) { ... }
and I have these interfaces:
public interface IMyInterface1 extends IMyBasicInterface { ... }
public interface IMyInterface2 extends IMyBasicInterface { ... }
and I have this set:
val interfacesSet = setOf(
IMyInterface1::class.java,
IMyInterface2::class.java)
I'd like to create an instance of GenericClass<T>
by writing something like this:
interfacesSet.forEach { currentInterface ->
val myObj = GenericClass<currentInterface>(param1, param2)
.... }
but of couse this won't compile.
How can I do this?
Let's say I have this class:
class GenericClass<T>(
private val param1: String = ""
private val param2: ((String, String) -> Unit)? = null
) { ... }
and I have these interfaces:
public interface IMyInterface1 extends IMyBasicInterface { ... }
public interface IMyInterface2 extends IMyBasicInterface { ... }
and I have this set:
val interfacesSet = setOf(
IMyInterface1::class.java,
IMyInterface2::class.java)
I'd like to create an instance of GenericClass<T>
by writing something like this:
interfacesSet.forEach { currentInterface ->
val myObj = GenericClass<currentInterface>(param1, param2)
.... }
but of couse this won't compile.
How can I do this?
Share Improve this question asked Nov 22, 2024 at 20:26 Marina FinettiMarina Finetti 1179 bronze badges 1- Why do you need to do this? Why can't you just make them GenericClass<IMyBasicInterface>? If you can't do that, what's the purpose of IMyBasicInterface ? – Gabe Sechan Commented Nov 22, 2024 at 20:40
2 Answers
Reset to default 0Create an extension function:
fun <T : IMyBasicInterface> Class<T>.createGenericClass(param1: String): GenericClass<T> {
return GenericClass<T>(param1)
}
And then use it like this:
interfacesSet.forEach { currentInterface ->
val myObj = currentInterface.createGenericClass(param1)
}
Generics are used to make compile-time guarantees about types. At runtime parameter types are erased and they don't matter anymore. GenericClass<IMyInterface1>
and GenericClass<IMyInterface2>
become exactly the same types.
Direct answer to the question would be to create a GenericClass<Any>(...)
, then use it in places that require e.g. GenericClass<IMyInterface1>
- if this is what you need. It should work without any problems.
Generally, it feels the question doesn't make too much sense. Either you have a rather rare corner case or you try using generics for something they weren't designed for.
本文标签: androidHow can I use a type parameter to create a generic objectStack Overflow
版权声明:本文标题:android - How can I use a type parameter to create a generic object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736301033a1931035.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论