在 Java 中什么是方法签名?
Definition: Two of the components of a method declaration comprise the method signature—the method’s name and the parameter types.
方法声明的两个组件构成了方法签名 - 方法的名称和参数类型。
example:
这里是一个典型的方法声明:
public double calculateAnswer(double wingSpan, int numberOfEngines,
double length, double grossTons) {
//do the calculation here
}
上面方法的签名是:calculateAnswer(double, int, double, double)
Signature
Signature是 Java 反射 API 中的一个接口,用于描述方法或构造函数的签名信息。
Spring AOP 中的 JoinPoint 接口继承了反射 API 中的 Member 接口,因此可以通过 JoinPoint 对象获取到方法或构造函数的 Signature 对象。
在 Spring AOP 中,切面可以通过 JoinPoint 对象获取到连接点的相关信息,其中包括方法签名信息,可以通过 JoinPoint 对象的 getSignature() 方法获取到 Signature 对象。
如果连接点是一个方法,那么可以将 Signature 对象转换为 MethodSignature 对象,通过 MethodSignature 对象可以获取到更加详细的方法签名信息,比如方法返回类型、参数类型等。
MethodSignature 表示方法的签名信息,包括方法名称、返回类型、参数类型等。它定义了一些方法,可以获取方法的相关信息,包括 getName() 方法用于获取方法名称、getReturnType() 方法用于获取方法返回类型、getParameterTypes() 方法用于获取方法参数类型列表等。
Method 类和MethodSignature 类
Method 类
Method 属于 Java 标准反射 API,位于 java.lang.reflect 包下。主要用于在运行时获取和操作类的方法,支持动态调用。
通过 Class 对象的 getMethod 等方法获取 Method 对象,用于获取方法的详细信息,如方法名称、返回类型、参数类型等。
MethodSignature 类
MethodSignature 属于 Spring AOP 框架,位于 org.aspectj.lang.reflect 包下。主要用于 Spring AOP 中,用于在切面中获取被代理方法的签名信息,方便切面进行条件匹配、日志记录等操作。
通过 JoinPoint 对象获取 MethodSignature 对象。用于获取切点方法的详细信息,如方法名称、返回类型、参数类型等。
Method 类和MethodSignature 类区别
框架不同
- Method 是 Java 标准反射 API 的一部分,用于在运行时获取和操作类的方法。
- MethodSignature 属于 Spring AOP 框架,用于在切面中获取连接点方法的签名信息。
获取方式不同
- 获取 Method 对象通常是通过 Class 对象的 getMethod 方法等标准反射方法获取的。
- 获取 MethodSignature 对象通常是通过 JoinPoint 对象的 getSignature 方法获取的。
用途不同
- Method 主要用于反射,支持动态调用和获取方法的元数据。
- MethodSignature 主要用于 Spring AOP,在切面中获取连接点方法的签名信息,方便切面进行条件匹配和日志记录等操作。
Java 中方法签名及相关类解析
168万+

被折叠的 条评论
为什么被折叠?



