面试题答案
一键面试import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
// 类的全限定名
String className = "java.util.ArrayList";
// 通过反射获取类对象
Class<?> clazz = Class.forName(className);
// 获取所有public方法
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
在上述代码中:
- 定义了一个类的全限定名
className
。 - 使用
Class.forName(className)
通过反射获取类对象clazz
。 - 调用
clazz.getMethods()
获取该类及其父类的所有public方法。 - 遍历并打印出所有的public方法。