将Scala反射与Java反射一起使用 [英] Using Scala reflection with Java reflection

查看:113
本文介绍了将Scala反射与Java反射一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为DSL的一部分,我有很多代码一直在使用Java反射来调用Java对象上用户指定的任意方法.

I have a lot of code that has been using Java reflection to invoke arbitrary user-specified methods on Java objects, as part of a DSL.

但是,实际上,其中的许多Java对象都是Scala对象,并且其中的某些方法都使用Scala @deprecated批注进行标记.不幸的是,Java的注释机制无法看到Scala注释,并且直到Scala 2.10为止(我知道吗?)没有方便的方法来访问这些注释.

However, a lot of those Java objects, in practice, are Scala objects, and some of the methods on them are marked with the Scala @deprecated annotation. Unfortunately, Java's annotations mechanism cannot see Scala annotations, and until Scala 2.10 there was no convenient way (that I know of?) to get access to those annotations.

我终于升级到2.10,并且希望能够从DSL发出弃用警告.但是,我不想重写整个求值器(至少现在是这样)以使用Scala反射,因此有一种简便的方法可以将java.lang.reflect.Method转换为可以使用Scala反射的值,以确定是否不建议使用Scala方法?还是我必须先使用Scala反射来复制很多现有的方法解析逻辑,然后才能获得该信息?

I have finally upgraded to 2.10, and would like to be able to emit deprecation warnings from my DSL. However, I don't want to rewrite the entire evaluator (for now, at least) to use Scala reflection, so is there a convenient way to go from a java.lang.reflect.Method to something I can use Scala reflection on to figure out if the Scala method in question is deprecated? Or will I have to duplicate a lot of the existing method resolution logic using Scala reflection before I can get at that information?

它看起来像曾经存在于Scala反射中的JavaToScala类,其中有一个methodToScala方法可以满足我的要求.我能找到的唯一跟踪记录是

It looks like a JavaToScala class used to exist in Scala reflection, which had a methodToScala method in it that did what I want. The only trace I can find is here, in a google code project. Why was the functionality moved out of core reflection? Or is it still there under a different name?

看起来该代码存在于scala.reflect.runtime.JavaMirrors中,但是不幸的是它是私有的(还有另一个JavaMirrors是公共API的一部分,但没有提供我需要的任何内容.)我如果存在通过公共API进行调用的路径",将我带到深埋在私有JavaMirrors中的私有methodAsScala,则无法确定我的生活.至少可以说,这令人沮丧:(

It looks like the code in question lives on in scala.reflect.runtime.JavaMirrors, but unfortunately it's private (there's another JavaMirrors that is part of the public API, but doesn't provide any of what I need.) I can't figure out for the life of me if there's a "path" of invocations through a public API that takes me all the way down to the private methodAsScala buried deep within the private JavaMirrors. It's frustrating, to say the least :(

推荐答案

这是一个快速解决方法(贷记@EugeneBurmako)

Here is a quick fix (credits to @EugeneBurmako)

https://gist.github.com/xeno-by/5277805

对此已提出问题(贷方为@MysteriousDan):

An issue has been filed for this (credits to @MysteriousDan):

https://issues.scala-lang.org/browse/SI-7317

这篇关于将Scala反射与Java反射一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆