Class类中的getDeclaredMethods()

Pus*_*raj 3 java reflection

public Method[] getDeclaredMethods() throws SecurityException
Run Code Online (Sandbox Code Playgroud)

有如下文件.

/**
     *
     * Returns an array containing {@code Method} objects reflecting all the
     * declared methods of the class or interface represented by this {@code
     * Class} object, including public, protected, default (package)
     * access, and private methods, but excluding inherited methods.

<p> If this {@code Class} object represents a type that has multiple
             * declared methods with the same name and parameter types, but different
             * return types, then the returned array has a {@code Method} object for
             * each such method.
         *
Run Code Online (Sandbox Code Playgroud)

单个类如何具有两个具有不同返回类型,相同名称和相同参数类型的[声明]方法?

Joa*_*uer 5

Java语言中,不可能声明两个具有相同名称和参数类型但返回类型不同的方法.

然而,Java虚拟机(JVM)处理方法没有问题.

有一种方法可以通过使用更具体的返回类型覆盖基类方法来隐式创建此类方法.

如果基类有一个方法Object foo()而你的类用方法覆盖它,String foo()那么.class你的类的文件将有一个合成的(因此不是"可见的")方法Object foo()和一个"普通"方法String foo().该Object foo()方法与要将您的类视为基类的实例并且不知道String foo()重写的类兼容.

此外,一些非Java语言可能允许您显式地使用这些方法创建类.