1

我正在使用一个调用 Java 库的小型 Groovy 脚本。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() ?

其他一些人已经被这个问题所困扰。来自Groovy 用户的这封电子邮件

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.
4

2 回答 2

0

解决了。

问题是,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
于 2013-06-13T17:46:14.253 回答
0

无法在 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()吗?

于 2013-06-13T16:39:02.670 回答