zno2

Java 方法签名 , method signature

为什么说方法签名,这是java 方法重载 (overload) 的唯一依据

https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

More generally, method declarations have six components, in order:

  1. Modifiers—such as publicprivate, and others you will learn about later.
  2. The return type—the data type of the value returned by the method, or void if the method does not return a value.
  3. The method name—the rules for field names apply to method names as well, but the convention is a little different.
  4. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
  5. An exception list—to be discussed later.
  6. The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.

 

方法签名由 方法名和参数类型列表组成

method signature—the method's name and the parameter types.

 

示例1:

这两个方法不能重载,因为方法签名一样

duplicate ['dju:plikət, 'dju:plikeit]

identically copied from an original

 

示例2

 

尽管 generic 泛型不同,但泛型只是用来编译时校验用的,方法签名还是一样

依据是什么?

import java.lang.reflect.Method;
import java.util.List;

public class Test {

    public void ff(List<Integer> s) {
        System.out.println(111);
    }

    public static void main(String[] args) throws ClassNotFoundException {
        //the array of Method objects representing the public methods of this class
        Method[] methods = Test.class.getMethods();
        for (Method method : methods) {
            if(!method.getName().equals("ff")){
                continue;
            }
            System.out.println("[" + method.getName() + "]");
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (Class<?> class1 : parameterTypes) {
                System.out.println(class1);
            }
        }
    }
}

输出结果:

[ff]
interface java.util.List

 下面这个方法没涉及到泛型,返回方法数组

 

可以这样理解:

方法签名就是  method.getParameterTypes() 和 method.getName()

posted on 2023-08-25 16:27  zno2  阅读(291)  评论(0编辑  收藏  举报

导航