Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

java - How to call MethodInvoke - reflection

If i have a method which takes a int[] as a parameter and i wish to call method.invoke on this then do i need to do the following

Object[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
method.invoke(obj, anArray);

Is it as simple as that as i seem to be getting errors?

Regards

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Method.invoke takes two arguments. The first is the target, obj, which is correct. The second is an array representing zero or more arguments for the actual method you are trying to invoke (many methods have more than one parameter). Your code should change to:

method.invoke(obj, new Object[] { anArray });

This way, you're saying "invoke this method with one argument, and that argument is an array. This is different from saying, "invoke this method with 10 arguments" (one for each element in your array).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...