简体   繁体   English

如何使用 Java 反射将原始类型值分配给方法 args?

[英]How to assign primitive type value to a method args using Java reflection?

I'm new to java reflection concept.我是 Java 反射概念的新手。 I need to access one method from a particular class using Java reflection.我需要使用 Java 反射从特定类访问一个方法。 That method has three different types of argument like this,该方法具有三种不同类型的参数,如下所示,

public void print(int start, String middle, int end) {
   System.out.println(start);
   System.out.println(middle);
   System.out.println(end);
}

I tried to call that method like this,我试着像这样调用那个方法,

...
method.invoke(null, "middle", null);
...

I got IllegalArgumentException .我得到了IllegalArgumentException I know null is acceptable for wrapper type args, but I just tried this method for knowing how it is working.我知道 null 对于包装类型 args 是可以接受的,但我只是尝试了这种方法来了解它是如何工作的。

So, my main question is, how to pass primitive type value to that method argument via reflection?所以,我的主要问题是,如何通过反射将原始类型值传递给该方法参数? also, how to pass default value for primitive type arg via reflection?另外,如何通过反射传递原始类型 arg 的默认值? (for eg: let's assume, I don't need end arg value during runtime, then how to pass 0 for end arg) (例如:让我们假设,我在运行时不需要结束 arg 值,那么如何为结束 arg 传递 0)

Is there any way to solve this issue?有没有办法解决这个问题?

Suppose that you have this class:假设你有这个类:

public class SomeClass {

    public void print(int start, String middle, int end) {
        System.out.println(start);
        System.out.println(middle);
        System.out.println(end);
    }

}

You can use the following code to:您可以使用以下代码:

  1. Instantiate the class using reflection使用反射实例化类
  2. Fetch the desired method获取所需的方法
  3. Call the desired method using reflection使用反射调用所需的方法
public class SomeOtherClass {

    public static void main(String... args) {
    try {
        var instance = Class
        .forName(SomeClass.class.getName())
        .getConstructor()
        .newInstance();
        var printMethod = SomeClass.class.getMethod("print", int.class, String.class, int.class);
        printMethod.invoke(instance, 0, "it's me", 0);
    } catch (NoSuchMethodException | ClassNotFoundException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
        System.err.println("An error has occurred while accessing method");
        e.printStackTrace();
    }
    }

}

Note that for primitive values there is no need to pass is null .请注意,对于原始值,无需传递 is null For those cases, you need to supply a value, which in turn means calling the method reflectively like so:对于这些情况,您需要提供一个值,这又意味着反射性地调用该方法,如下所示:

printMethod.invoke(instance, 0, "it's me", 0);

Note that this would be the same as calling the method directly, as in this case as well attempting to pass in null as method argument for integers would result in a compilation error.请注意,这与直接调用方法相同,因为在这种情况下,尝试将null作为整数的方法参数传递将导致编译错误。

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

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