Java 反射获取 String 类方法、构造方法和变量详解

使用反射可以获取类中的方法、构造方法和变量,并进行动态调用。以下代码示例展示了如何使用反射获取 String 类的所有方法、构造方法和变量,并调用其中的 length() 方法。

步骤

  1. 获取 String 类的 Class 对象:
Class<?> stringClass = String.class;
  1. 获取 String 类的所有方法:
Method[] methods = stringClass.getDeclaredMethods();
  1. 打印所有方法名:
for (Method method : methods) {
    System.out.println(method.getName());
}
  1. 获取 String 类的所有构造方法:
Constructor<?>[] constructors = stringClass.getDeclaredConstructors();
  1. 打印所有构造方法名:
for (Constructor<?> constructor : constructors) {
    System.out.println(constructor.getName());
}
  1. 获取 String 类的所有变量:
Field[] fields = stringClass.getDeclaredFields();
  1. 打印所有变量名:
for (Field field : fields) {
    System.out.println(field.getName());
}
  1. 调用 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();
}

注意事项

使用反射调用方法、构造方法和变量时,需要处理可能抛出的异常,例如 NoSuchMethodExceptionIllegalAccessExceptionInvocationTargetException

总结

以上代码演示了如何使用 Java 反射获取 String 类的所有方法、构造方法和变量,并调用 length() 方法获取字符串长度。反射是一种强大的工具,可以用于动态操作类和对象,但使用时要注意处理异常。

Java 反射获取 String 类方法、构造方法和变量详解

原文地址: https://www.cveoy.top/t/topic/qd6Q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录