简体   繁体   中英

Java reflection: passing an integer argument

I'm learning about reflection in java and I tried a simple reflected class, but an exception happened:

java.lang.NoSuchMethodException : it.accaemme.exercises.MaxDiTre.MaxDiTre.absDigit(java.lang.Integer)

Any suggest? Thanks

Here code:

/* /src/main/java/.../ */
/* filename: MaxDiTre.java */

package it.accaemme.exercises.MaxDiTre;

public class MaxDiTre {
    public static int max(int num1, int num2, int num3) {
     /* some stupid stuffs */
   }
    
   private int absDigit(int n) {
       return Math.abs(n);
   }
}
/* ------------ */
public class TestMaxDiTre {
    /*...*/

    // Test16:  class test
    MaxDiTre mdt;
    @Before
    public void AlphaTest() {
        mdt = new MaxDiTre();
    }
    
    // non funziona
    // Test17:  test private method: absDigit()
    @Test
    public void testPrivateMethod_absDigit(){
            Method m;
            try {
                //Class<?> argTypes = new Class() { Integer.class }
                //Class<?> argTypes = Integer.class;
                //Class<?> argTypes = null;
                //@SuppressWarnings("deprecation")
                //Class<int>[] argTypes = null;
                //Class<?>[] argTypes = (Class<?>[]) null;
                //Class<?>[] argTypes = null;
                //int argTypes = (Class<?>[])8;
                //m = MaxDiTre.class.getDeclaredMethod("absDigit", argTypes );
                m = mdt.getClass().getDeclaredMethod("absDigit", argTypes);
                m.setAccessible(true);
                assertEquals(
                         8,
                         (int)m.invoke(
                                        mdt, -8
                                    )
                        );
            } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    }
}

You want int.class . Something like,

public static void main(String[] args) {
    Class<?> clazz = MaxDiTre.class;
    Method m;
    try {
        m = clazz.getDeclaredMethod("absDigit", int.class);
        m.setAccessible(true);
        System.out.println((int) m.invoke(new MaxDiTre(), -8));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Outputs

8

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