0

I have used all the suggestions I could find on StackOverflow and other sites for this. I am trying to invoke a method using reflection. Here is the code for my method:

public void my_method(String[] args) {

    for(int i=0; i<args.length; i++)
    {
        System.out.println(args);
    }
}

Here is the code I used for reflection

Class[] paramStringArray = new Class[1];    
paramStringArray[0] = String[].class;
String[] argu = {"hey", "there"};

Method method = cls.getDeclaredMethod("my_method", paramStringArray);
method.invoke(obj, new Object[]{argu});

My issue is that when I run the program, I see the output printed as: [Ljava.lang.String;@70a6aa31 [Ljava.lang.String;@70a6aa31

I have tried all the suggestions I could find. Can someone please help me with this?

Thanks!

2
  • Object#toString() is your keyword. Why are you trying the advanced topic of reflection when you don't yet know how to print an object? Slow down. Commented Jul 24, 2013 at 20:04
  • args is a String[]. It does not have a custom toString() method to print its contents. Use Arrays.toString(args); to return a String with the contents of the array. Commented Jul 24, 2013 at 20:18

2 Answers 2

1

The method my_method() receives as a parameter a String[], not a String. You're calling a different method. The code should look like this:

paramString[0] = String[].class;
Method method = cls.getDeclaredMethod("my_method", paramString);

To invoke it, pass a String[] as parameter:

method.invoke(obj, new String[]{"x"});

Also, the body of the loop in my_method() should refer to each element's position, not to the array itself:

System.out.println(args[i]);
Sign up to request clarification or add additional context in comments.

5 Comments

Maybe paramStringArray is String[].class.
I'm betting the code was not copied correctly, so it's hard to know what's the real problem
Well, I tried Object#toString() before posting this question. Thanks, for the suggestion though
Sorry, my bad in typing the code. I actually have it the way you mentioned. I will edit the question.
@user2033666 ok, if that was not the problem then look at the last part in the answer - you're printing the array and not the contents of the array, use this to fix it: System.out.println(args[i]);
1

You need to print args[i] and not what you have.

Also the method should be called with a new String[] instead of new Object[].

1 Comment

Oh!! that was a really silly typo I made.. I changed it to args[i] and it works great now. :) Thanks so much for noticing that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.