简单示例:Java反射机制理解及应用

原创 ゞ 浴缸里的玫瑰 2024-12-02 09:48 100阅读 0赞

Java反射机制是一种动态获取和操作对象信息的手段。它允许我们在运行时查看类、方法和字段等信息,并进行调用。

以下是一个简单的示例:

  1. // 创建一个类
  2. public class Student {
  3. // 创建一个私有属性
  4. private String name;
  5. // 创建一个公开的方法
  6. public void study() {
  7. System.out.println("Student is studying");
  8. }
  9. }
  10. // 使用反射获取信息
  11. import java.lang.reflect.Method;
  12. public class ReflectionExample {
  13. public static void main(String[] args) {
  14. // 获取Student类
  15. Class<Student> clazz = Student.class;
  16. // 创建Student对象
  17. Student student = new Student();
  18. student.name = "John Doe";
  19. // 定义一个公开方法
  20. Method method = clazz.getMethod("study");
  21. // 调用反射的方法
  22. method.invoke(student);
  23. System.out.println("学生信息:" + student.name);
  24. }
  25. }

在这个示例中,我们首先创建了一个Student类,并在其中定义了一个私有属性和一个公开方法。然后,我们使用反射获取了这个类以及它的方法,最后调用了这个方法并打印出了结果。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,100人围观)

还没有评论,来说两句吧...

相关阅读