Java:通过反射调用静态方法、非静态方法

  • 示例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中");
    }
}

运行输出:
在这里插入图片描述

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值