1. To call a static method
Class> threadClazz = Class.forName("java.lang.Math"); Method method = threadClazz.getMethod("abs", long.class); System.out.println(method.invoke(null, -10000l));
Just set the first parameter of the invoke method to null.
2. Call the constructor method in the class
Obtain the constructor of the specified parameter type in the class
public Constructor getConstructor(Class>… parameterTypes) throws NoSuchMethodException, SecurityException
Can only obtain public permissions in the class The constructor method
public Constructor getDeclaredConstructor(Class>… parameterTypes)
can obtain all the constructor methods in the class, including private constructors.
3. Call the ordinary method with the specified name in the class
public Method getMethod(String name, Class>… parameterTypes) //方法有重载所以要传名称和参数类型取得本类以及父类中所有public方法 public Method getDeclaredMethod(String name, Class..parameterTypes) 取得本类中全部普通方法,包括私有方法。
The above is the detailed content of How to call a method using Java reflection?. For more information, please follow other related articles on the PHP Chinese website!