JDK クラスにコードを挿入しようとしていInteger
ます。インジェクションは、Groovy 内にいる限り機能しますが、Java クライアントからインジェクトされたコードを使用しようとすると機能しません。
これが問題のデモです。
次のGroovyコード...
// File: g.groovy
class G {
public static void init() {
println 'Constructor injected';
java.lang.Integer.metaClass.constructor = { i ->
println "My constructor called for Integer($i)"
def constructor = Integer.class.getConstructor(int.class)
constructor.newInstance(i)
}
}
public static void main(String[] args) {
G.init();
}
}
println 'Before injection'
new Integer(1);
G.init()
new Integer(1);
...正しい出力が得られます:
$ groovy g.groovy
Before injection
Constructor injected
My constructor called for Integer(1)
$
今、私はg.groovy
EXCEPTからすべてを削除しますclass G
:
// File: g.groovy
class G {
public static void init() {
println 'Constructor injected';
java.lang.Integer.metaClass.constructor = { i ->
println "My constructor called for Integer($i)"
def constructor = Integer.class.getConstructor(int.class)
constructor.newInstance(i)
}
}
public static void main(String[] args) {
G.init();
}
}
次に、コンパイルしますg.groovy
。
$ groovyc g.groovy
$ ls *.class
G.class G$_init_closure1.class
$
次に、からの注入を利用しようとしますU.java
:
// U.java
public class U {
public static void main(String[] args) {
System.out.println("Creating a new integer");
new Integer(1);
G.init();
System.out.println("Creating a new integer");
new Integer(1);
}
}
そして、私が得る結果はこれです:
$ javac U.java
$ java -cp .:/path/to/groovy/embeddable/groovy-all-2.1.7.jar U
Creating a new integer
Constructor injected
Creating a new integer
$
注射は明らかに効きませんでした!