是否可以有“方法/字段”?与 Java/Scala 中的类文字相当的文字吗?
Java 的 Foo.class
以及 Scala 的 classOf[Foo]
文字类语法返回有关相关类的反射视图。
提供诸如 .method/.field
或 methodOf[]
/fieldOf[]
之类的内容来获得可比较的反射是否可能并且有意义吗?访问方法和字段?
在 Java/Scala 中如何实现这样的事情?
就 Java 而言,我认为这要么需要更改语言(非常不可能),要么需要使用字节码工具/AspectJ 进行一些操作,而在 Scala 中,可能可以通过隐式转换来实现它。
Java's Foo.class
as well Scala's classOf[Foo]
literal class syntax return a reflective view about the class in question.
Is it possible and would it make sense to provide something like .method/.field
or methodOf[]
/fieldOf[]
for getting comparable reflective access to methods and fields?
How would something like this be implemented in Java/Scala?
In the case of Java, I would assume that this would either require a language change (very unlikely) or some wizardry with bytecode tools/AspectJ, whereas in Scala it is probably possible to implement it with an implicit conversion.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是和不是。 Paul Phillips 确实表达了对这样的事情的兴趣,并且目前在主干中围绕即将到来的 scala 反射正在进行大量工作。
不过,我们是否会看到类似您建议的语法的内容值得怀疑。方法不是一流的构造,因此只能通过其包含类来引用。但是我们将获得一种很好的 scala 友好方式来通过反射访问成员,包括默认参数、参数名称等。
Yes and no. Paul Phillips has certainly expressed an interest in such a thing, and there's a lot of work currently happening in trunk around the forthcoming scala reflections.
It's doubtful that we'll see anything like your proposed syntax though. Methods are not a first-class construct and, as such, and only be referenced via their containing class. But we will be getting a nice scala-friendly way to access members via reflection, including default params, parameter names, etc.
我不记得在哪里,但我最近偶然发现了一个 Java 库,它将 Java 类作为输入并生成一个元类,可以这么说,它有静态字段(我认为),它们是对所有字段和方法的引用目标班级。它当然不像您正在寻找的那样优雅,但它给我留下了深刻的印象,因为它是一种潜在有用的魔法。
I don't recall where, but I stumbled across a Java library recently that would take Java classes as input and generate a metaclass, so to speak, that had static fields (I think) that were references to all of the fields and methods on the target class. It's certainly not as elegant as what you're looking for, but it struck me as a potentially useful bit of wizardry.