C# 什么是反射
发布日期:2021-05-10 05:06:05 浏览次数:23 分类:精选文章

本文共 2608 字,大约阅读时间需要 8 分钟。

��������������� Java ������������������������������������������������������������������������������������������������������������������������������������������������������

���������������

���������������������������������������Type������������������

Class
type = MyClass.class;

������Type��������������������������������������������������������������� annotations������������������������������������

  • ������������������

    String className = type.getName(); // ������������
  • ������������������������

    boolean isInterface = type.isInterface(); // true���������������

������������������

���������������������������������������������������������������������

Method method = type.getMethod("methodName");

���������������������������������������������������������������������������������������������������������MethodNotFoundException���NoSuchMethodException���

������������

���������������������������

public class MyClass {
public void sayHello() {
}
}

������������������������������

Object instance = new MyClass();
Method method = MyClass.class.getMethod("sayHello");
method.invoke(instance); // successfully

������������������������������������

Object instance = new MyClass();
Method method = instance.getClass().getMethod("sayHello");
method.invoke(instance); // successfully

������������������

���������������������������������������������������������������������������������������������������������������������������������������������������������

  • ���������������������������

    for (Method method : type.getMethods()) {
    System.out.println(method.getName());
    }
  • ���������������������������

    for (Method method : type.getMethods()) {
    try {
    Object result = method.invoke(type������ null);
    System.out.println("- " + method.getName() + "() return: " + result);
    } catch (IllegalAccessException e) {
    System.out.println("������������ " + method.getName() + "() ������");
    }
    }
  • ������������

    • ������������������������������������������������������������������������������������������������������

      AccessibleObject accessibleObject = method.getAccessible();
      if (accessibleObject.isAccessible()) {
      // ���������
      } else {
      method.setAccessible(true);
      }
    • ��������������������������������������������������������������� method.getModifiers() ������������������������������

    ������

    ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

    上一篇:C# 如何反射方法
    下一篇:如何给C#应用程序添加应用图标

    发表评论

    最新留言

    不错!
    [***.144.177.141]2025年04月28日 14时18分31秒