Home  >  Article  >  Java  >  How to call a method using Java reflection?

How to call a method using Java reflection?

WBOY
WBOYforward
2023-04-24 14:22:071961browse

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete