转自:
下文讲述使用Java反射获取一个类中“所有方法”的方法分享,如下所示:
实现思路:
1.forName():获取指定的Class对象
2.getMethods();
或
getDeclaredMethods();
3.使用Method对象的invoke方法接口运行指定方法
例:
package com.java265.other;
import java.lang.reflect.Method;
public class TestClass {
public static void main(String[] args) throws Exception {
Class> clazz = Class.forName("com.java265.other.User");
Method method1 = clazz.getMethod("testFun2", null);
method1.invoke(null, null);
}
}
class User {
public User() {
}
public static void testFun2() {
System.out.println("我是方法testFun2");
}
}
-----运行以上代码,将输出以下信息-----
我是方法testFun2