我正在使用一个小的Groovy脚本来调用Java库。 Java库具有方法m(String,int)
,其中第二个参数是int基本类型。
下面的脚本创建一个新的int变量,并尝试调用该方法。
int year = 2013
def obj = dao.m("johndoe", year)
但是失败,因为第二个参数的类型是java.lang.Integer
包装器,而不是原始int:groovy.lang.MissingMethodException: No signature of method: com.sun.proxy.$Proxy11.m() is applicable for argument types: (java.lang.String, java.lang.Integer) values: [IN-94158-11, 2013]
我如何声明一个变量来保存原始int,以便可以调用方法m()?
[其他人被这个问题咬了。从此email in Groovy Users:
As we stated earlier, it doesn’t matter whether you declare or cast a variable to be
of type int or Integer. Groovy uses the reference type (Integer) either way.
已解决。
问题是,JNDI查找的结果还不是远程对象,而是将实例化到远程对象的代理的EJBHome对象。
这样,对方法查找的调用结果没有方法m()。相反,它具有方法remove()
,create()
,getEJBObject()
,getEJBMetadata()
等。
因此,我的脚本变为:
// def dao = ctx.lookup("MyDao") // WRONG ! Result of JNDI lookup returns an EJBHome,
// not a proxy to the remote object
def dao = ctx.lookup("MyDao").create() // OK. This is a proxy to the remote object.
dao.m("johndoe", 2013) // OK. Groovy DOES call the correct method,
// which takes an int.
我应该早先检查对象的类及其方法:
dao.class
dao.class.methods
无法在Groovy 2.1.3,JDK 7上复制以下内容:
// file EjbImpl.java
import java.lang.reflect.*;
public class EjbImpl {
private EjbImpl() {}
public Ejb newInstance() {
return (Ejb) Proxy.newProxyInstance(
EjbImpl.class.getClassLoader(),
new Class[] { Ejb.class },
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) {
System.out.println("invoke " + method);
return args.toString();
}
}
);
}
public void process(int i) {
System.out.println("ejb.process = " + i);
}
}
// Ejb.java
public interface Ejb {
public void process(int i);
}
// EjbTest.groovy
ejb = EjbImpl.newInstance()
ejb.process new Integer(90)
我必须承认我不确定这是否是EJB创建代理的方式...
您是否尝试过year.intValue()
?