How to work with varargs and reflection

后端 未结 2 429
野性不改
野性不改 2020-11-28 10:10

Simple question, how make this code working ?

public class T {

    public static void main(String[] args) throws Exception {
        new T().m();
    }

            


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 10:23

    Test.class.getDeclaredMethod("foo", String[].class);
    

    works. The problem is that getMethod(..) only searches the public methods. From the javadoc:

    Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

    Update: After successfully getting the method, you can invoke it using:

    m.invoke(this, new Object[] {new String[] {"a", "s", "d"}});
    

    that is - create a new Object array with one element - the String array. With your variable names it would look like:

    m.invoke(this, new Object[] {a});
    

提交回复
热议问题