[英]Scala check at runtime whether an object has a the same type as a given parameterized type of a method invocation
I have a type called T and some subclasses (forgive me if this is not the correct terminology) of T called T1, T2, T3, etc. 我有一个名为T的类型和T的一些子类(如果这不是正确的术语,请原谅我)称为T1,T2,T3等。
I want to write a method that 我想写一个方法
The first approach that comes to mind is as follows, but it is defeated by runtime type erasure. 我想到的第一种方法如下,但它被运行时类型擦除所击败。
elements.filter(_.isInstanceOf[S])
Can someone please provide some insight on what would be the simplest way to achieve this? 有人可以提供一些有关实现这一目标的最简单方法的见解吗? Looking into this on Google suggests that it is doable by having my method take a java.lang.Class
as an argument and doing runtime reflection with java.lang.reflect
related classes. 在Google上进行调查表明,通过让我的方法将java.lang.Class
作为参数并使用java.lang.reflect
相关类进行运行时反射,可以实现这一点。 That seems like it is too generic, though. 但这似乎太过一般了。
That is to say, I know what type I want to filter for at the call site. 也就是说,我知道我想在呼叫站点过滤哪种类型。 I would ideally want to be able to call, say, something like getInstancesOf[S]
because I statically know what SI want at the call site. 理想情况下,我希望能够调用getInstancesOf[S]
这样的东西,因为我静静地知道SI在呼叫站点需要什么。
Thanks in advance! 提前致谢!
I ended up finding the answer in another StackOverflow question . 我最终在另一个StackOverflow问题中找到了答案。 I initially missed it because of how I was framing the question. 我最初错过了它,因为我正在构思这个问题。
The outline of the answer is: 答案的大纲是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.