Skip to content

Commit 9d9d0cc

Browse files
juarezjaramilloKevinGilmore
authored andcommitted
BAEL-870 How to call a method during runtime using reflection? (eugenp#1769)
* BAEL 870 How to call method during runtime using reflection? * BAEL-870 How to call a method during runtime using reflection?
1 parent 14f90c8 commit 9d9d0cc

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.java.reflection;
2+
3+
public class Operations {
4+
5+
public double sum(int a, double b) {
6+
return a + b;
7+
}
8+
9+
public static double multiply(float a, long b){
10+
return a * b;
11+
}
12+
13+
private boolean and(boolean a, boolean b) {
14+
return a && b;
15+
}
16+
17+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.baeldung.java.reflection;
2+
3+
import java.lang.reflect.InvocationTargetException;
4+
import java.lang.reflect.Method;
5+
import org.testng.Assert;
6+
import org.testng.annotations.Test;
7+
8+
public class OperationsUnitTest {
9+
10+
public OperationsUnitTest() {
11+
}
12+
13+
@Test(expectedExceptions = IllegalAccessException.class)
14+
public void givenObject_whenInvokePrivatedMethod_thenFail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
15+
Method andInstanceMethod = Operations.class.getDeclaredMethod("and", boolean.class, boolean.class);
16+
17+
Operations operationsInstance = new Operations();
18+
Boolean result = (Boolean)andInstanceMethod.invoke(operationsInstance, true, false);
19+
20+
Assert.assertFalse(result);
21+
}
22+
23+
@Test
24+
public void givenObject_whenInvokePrivateMethod_thenCorrect() throws Exception {
25+
Method andInstanceMethod = Operations.class.getDeclaredMethod("and", boolean.class, boolean.class);
26+
andInstanceMethod.setAccessible(true);
27+
28+
Operations operationsInstance = new Operations();
29+
Boolean result = (Boolean)andInstanceMethod.invoke(operationsInstance, true, false);
30+
31+
Assert.assertFalse(result);
32+
}
33+
34+
@Test
35+
public void givenObject_whenInvokePublicMethod_thenCorrect() throws Exception {
36+
Method sumInstanceMethod = Operations.class.getMethod("sum", int.class, double.class);
37+
38+
Operations operationsInstance = new Operations();
39+
Double result = (Double)sumInstanceMethod.invoke(operationsInstance, 1, 3);
40+
41+
Assert.assertTrue(4 == result);
42+
}
43+
44+
@Test
45+
public void givenObject_whenInvokeStaticMethod_thenCorrect() throws Exception {
46+
Method multiplyStaticMethod = Operations.class.getDeclaredMethod("multiply",float.class, long.class);
47+
48+
Double result = (Double)multiplyStaticMethod.invoke(null, 3.5f, 2);
49+
50+
Assert.assertTrue(7 == result);
51+
}
52+
53+
}

0 commit comments

Comments
 (0)