Java反射:传递一个整数参数



我正在学习java中的反射,我尝试了一个简单的反射类,但出现了一个异常:

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

有什么建议吗?感谢

此处代码:

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

您需要int.class。类似

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

输出

8

最新更新