在Java中,可以通过反射来获取被@Override注解标注的方法。以下是一种实现方式:

  1. 使用Class对象的getMethods()方法获取该类及其父类中公共方法的数组。
  2. 遍历方法数组,使用getDeclaredAnnotations()方法获取每个方法上的所有注解。
  3. 遍历注解数组,判断注解类型是否为Override,如果是,则表示该方法被@Override注解标注。

以下是一个示例代码:

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) {
        Class<MyClass> clazz = MyClass.class;

        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            Annotation[] annotations = method.getDeclaredAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation.annotationType() == Override.class) {
                    System.out.println("Method " + method.getName() + " is annotated with @Override");
                }
            }
        }
    }
}

class MyClass {
    @Override
    public void myMethod() {
        // 方法实现
    }
}

输出结果:

Method myMethod is annotated with @Override

在上述代码中,MyClass类中的myMethod()方法被@Override注解标注,在Main类中使用反射获取到该方法,并判断其是否被@Override注解标注。

java 中如何通过反射得到Override的方法?

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

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