import java.lang.reflect.*; public class Person { private void printName(String name) { System.out.println("Name: " + name); } public static void main(String[] args) throws Exception { Person p = new Person(); Method m = Person.class.getDeclaredMethod("printName", String.class); m.setAccessible(true); m.invoke(p, "John"); } }
import java.lang.reflect.*; public class Math { public static int add(int a, int b) { return a + b; } public static void main(String[] args) throws Exception { Method m = Math.class.getDeclaredMethod("add", int.class, int.class); System.out.println("Method: " + m); } }In this example, we use the getDeclaredMethod() method to obtain a Method object that represents the "add" method in the Math class. We pass in the name of the method as well as the parameter types as arguments. We then print out the Method object to the console to verify that we have obtained the correct method. In terms of package library, the getDeclaredMethod() method is part of the java.lang.reflect package.