简体   繁体   English

Scala在运行时检查对象是否与方法调用的给定参数化类型具有相同的类型

[英]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 我想写一个方法

  • takes in a collection of Ts 收集Ts
  • takes (preferably as a type parameter of the method) a type S <: T 采用(优选作为方法的类型参数)类型S <:T
  • returns the elements of the input collection that are of type S 返回S类型的输入集合的元素

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: 答案的大纲是:

  • The method takes an implicit ClassTag 该方法采用隐式ClassTag
  • The compiler substitutes the appropriate ClassTag into the value of the implicitly call 编译器将适当的ClassTag替换为隐式调用的值
  • At runtime, the runtime class of the objects in question are checked against the ClassTag 在运行时,将针对ClassTag检查相关对象的运行时类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM