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

How to call a method using Java reflection?

WBOY
Release: 2023-04-24 14:22:07
forward
2076 people have browsed it

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));
Copy after login

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
Copy after login

Can only obtain public permissions in the class The constructor method

public Constructor getDeclaredConstructor(Class<?>… parameterTypes)
Copy after login

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)
取得本类中全部普通方法,包括私有方法。
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template