Java 反射获取 String 类方法、构造方法和变量详解
Java 反射获取 String 类方法、构造方法和变量详解
使用反射可以获取类中的方法、构造方法和变量,并进行动态调用。以下代码示例展示了如何使用反射获取 String 类的所有方法、构造方法和变量,并调用其中的 length() 方法。
步骤
- 获取 String 类的 Class 对象:
Class<?> stringClass = String.class;
- 获取 String 类的所有方法:
Method[] methods = stringClass.getDeclaredMethods();
- 打印所有方法名:
for (Method method : methods) {
System.out.println(method.getName());
}
- 获取 String 类的所有构造方法:
Constructor<?>[] constructors = stringClass.getDeclaredConstructors();
- 打印所有构造方法名:
for (Constructor<?> constructor : constructors) {
System.out.println(constructor.getName());
}
- 获取 String 类的所有变量:
Field[] fields = stringClass.getDeclaredFields();
- 打印所有变量名:
for (Field field : fields) {
System.out.println(field.getName());
}
- 调用 String 类的
length()方法:
try {
Method lengthMethod = stringClass.getDeclaredMethod('length');
String str = 'Hello';
int length = (int) lengthMethod.invoke(str);
System.out.println('String length: ' + length);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
注意事项
使用反射调用方法、构造方法和变量时,需要处理可能抛出的异常,例如 NoSuchMethodException、IllegalAccessException 和 InvocationTargetException。
总结
以上代码演示了如何使用 Java 反射获取 String 类的所有方法、构造方法和变量,并调用 length() 方法获取字符串长度。反射是一种强大的工具,可以用于动态操作类和对象,但使用时要注意处理异常。
原文地址: https://www.cveoy.top/t/topic/qd6Q 著作权归作者所有。请勿转载和采集!