Eclipse里面有包下面的测试类调用默认包下面的类里面的方法

本文介绍了如何使用Java反射机制通过Class类的静态方法或类加载器获取类的所有公共方法,并调用指定方法。提供了两种方式:一是利用Class类的静态方法forName加载类;二是通过当前对象的类加载器获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、通过Class的静态方法获取.

Class clazz = Class.forName("类名");//将传入的类名所指定的类load到JVM内存中
Method[] methods = clazz.getMethods();//获取该相关类所有的public类型的方法
for (Method method : methods) {
  method.invoke(clazz.newInstance());//执行该对象的无参构造方法来创建该类的实例调用方法
}
Method method = clazz.getMethod("方法名");//根据方法名获取该相关类的public类型的方法
method.invoke(clazz.newInstance());

2、通过类的加载器

ClassLoader classLoader = this.getClass().getClassLoader();//获取当前对象的类装载器
Class clazz1 = classLoader.loadClass("类名");//通过类装载器加载需要的类

Method[] methods = clazz1.getMethods();
for (Method method : methods) {
  method.invoke(clazz1.newInstance());
}
Method method = clazz1.getMethod("方法名");
method.invoke(clazz1.newInstance());

转载于:https://www.cnblogs.com/bd195746/p/5813787.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值