0

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();
            }

    }
}

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.