简体   繁体   English

在将Java反射与Double []作为参数一起使用时,获取noSuchMethodException

[英]Getting noSuchMethodException when using java reflection with Double[] as argument

I have the following method signature: 我有以下方法签名:

public synchronized List<Bet> acceptTheBets(Double[] odds, BrokerState bs)

I am trying to use reflection to invoke this method, however I get the following exception: 我正在尝试使用反射调用此方法,但是出现以下异常:

java.lang.NoSuchMethodException: regions.BettingCenter.acceptTheBets([D, entities.BrokerState) java.lang.NoSuchMethodException:区域.BettingCenter.acceptTheBets([D,实体.BrokerState)

Why does it result in NoSuchMethodException ? 为什么会导致NoSuchMethodException

Here is a quick example on how to use this 这是有关如何使用此功能的快速示例

public class A {
    public static void main(String[] args) {
        try {
            Object a = new double[]{1.0, 2.0};
            System.out.println(A.class.getMethod("getStrings", double[].class).invoke(new A(), a));
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public synchronized List<String> getStrings(double[] array){
        return DoubleStream.of(array).boxed().map(d -> "" + d).collect(Collectors.toList());
    }

}

Notice the Object used to prevent that a is seen as 2 parameter for the varargs. 请注意,用于防止将a视为varargs的2参数的Object Also, you need to pass an instance to invoke the method in it. 另外,您需要传递一个实例以在其中调用该方法。

This works also for Double[] but need to pass the specific type Double[].class to get the correct method. 这也适用于Double[]但需要传递特定类型Double[].class以获得正确的方法。

public String getStrings(double[] array){
    return "double[]";
}

public String getStrings(Double[] array){
    return "Double[]";
}

Will be called with : 将被调用:

//double[]
A.class.getMethod("getStrings", double[].class)
    .invoke(new A(), (Object)new double[]{1.0, 2.0}));

//Double[]
A.class.getMethod("getStrings", Double[].class)
    .invoke(new A(), (Object)new Double[]{1.0, 2.0}));

Notice the differences of types and arguments passed. 注意传递的类型和参数的差异。

[D is double[] not Double[] . [Ddouble[]不是Double[] check https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.3.2 . 检查https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.3.2 It looks you are passing argument with wrong type. 看来您传递的参数类型错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM