scala反射场类
我试图获取引用自定义类的属性的类型,我只是得到它的类型是 Object
我的代码:
class Edge[N <% Node](var from : N, var to : N) {
def toXml(c: Class): xml.Elem = {
<edge>{
for(field: Field <- classOf[this.type].getDeclaredFields)
yield <field name={field.name} tpe={field.tpe.toString()}>{ this.getClass().getMethods.find(_.getName() == field.name).get.invoke(this) }</field>
}</edge>
}
所以这里的问题是我需要在 java 字段和 scala 字段之间切换:显然有scala 中没有 this.getClass 这样的东西吗?那么我需要通过Java来获取类吗? 然而,这似乎只会导致对象作为类型?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:修改后的问题是:应该使用 scala.reflect.Field 还是 java.lang.reflect.Field?
答案:总是[*]使用java.lang.reflect.Field,并且一般来说java反射有两个原因:
。
[*] 至少现在是这样。 Scala 即将推出反射。
--
原始答案:
如果您也发布了类代码,将会有所帮助,但该字段似乎被声明为 Object。 getType 返回字段的声明类。
来自 Field#getType( ):
如果您想要
实例的类型,那么您必须以正常方式在实例上执行 .getClass() 。
EDIT: The revised question is: Should scala.reflect.Field or java.lang.reflect.Field be used?
Answer: Always[*] use java.lang.reflect.Field, and in general java reflection for two reasons:
.
[*] At least for now. reflection is coming soon to Scala.
--
Original answer:
It would help if you posted the class code as well, but it seems that the field is declared as Object. getType returns the declaration class of the field.
From Field#getType():
gives
If you want the type of the instance, then you will have to do a .getClass() on the instance in the normal way.