Annotations and Reflection
Method Lookup
Reflection can locate a method by name and parameter types, then invoke it.
Method Lookup
MethodLookup.java
import java.lang.reflect.Method;
public class MethodLookup {
static class Calculator {
static int twice(int value) {
return value * 2;
}
}
public static void main(String[] args) throws Exception {
int value = ;
Method method = Calculator.class.getDeclaredMethod("twice", int.class);
int result = (int) method.invoke(null, value);
System.out.println("result=" + result);
}
}
import java.lang.reflect.Method;
public class MethodLookup {
static class Calculator {
static int twice(int value) {
return value * 2;
}
}
public static void main(String[] args) throws Exception {
int value = ;
Method method = Calculator.class.getDeclaredMethod("twice", int.class);
int result = (int) method.invoke(null, value);
System.out.println("result=" + result);
}
}
import java.lang.reflect.Method;
public class MethodLookup {
static class Calculator {
static int twice(int value) {
return value * 2;
}
}
public static void main(String[] args) throws Exception {
int value = ;
Method method = Calculator.class.getDeclaredMethod("twice", int.class);
int result = (int) method.invoke(null, value);
System.out.println("result=" + result);
}
}
method metadata
A Method object describes one method, including its name and parameter list.
invoke
Calling invoke runs the reflected method with the supplied receiver and arguments.