- 示例1:调用静态方法
下面的代码中,通过反射获取了Demo6 这个类的静态方法staticSayHello的对象,通过这个方法对象调用该方法的时候不需要创建Demo6 对象。
package com.thb;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Demo6 {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Object targetObject = null;
Method method = Demo6.class.getDeclaredMethod("staticSayHello");
// 判断如果该方法不是静态方法,则创建该方法声明类的对象
if (!Modifier.isStatic(method.getModifiers())) {
targetObject = Demo6.class.getDeclaredConstructor().newInstance();
}
// 通过反射进行方法调用
method.invoke(targetObject);
}
public static void staticSayHello() {
System.out.println("在静态函数staticSayHello中");
}
public void sayHello() {
System.out.println("在非静态函数sayHello中");
}
}
运行输出:
- 示例2:调用非静态方法
下面的代码中,通过反射获取了Demo6 这个类的非静态方法sayHello的对象,通过这个方法对象调用该方法的时候需要创建Demo6 对象。
package com.thb;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Demo6 {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Object targetObject = null;
Method method = Demo6.class.getDeclaredMethod("sayHello");
// 判断如果该方法不是静态方法,则创建该方法声明类的对象
if (!Modifier.isStatic(method.getModifiers())) {
targetObject = Demo6.class.getDeclaredConstructor().newInstance();
}
// 通过反射进行方法调用
method.invoke(targetObject);
}
public static void staticSayHello() {
System.out.println("在静态函数staticSayHello中");
}
public void sayHello() {
System.out.println("在非静态函数sayHello中");
}
}
运行输出: