简体   繁体   中英

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

I'm new to java reflection concept. I need to access one method from a particular class using Java reflection. 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 . I know null is acceptable for wrapper type args, but I just tried this method for knowing how it is working.

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? (for eg: let's assume, I don't need end arg value during runtime, then how to pass 0 for end arg)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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