gpt4 book ai didi

java - 扩大 Method 类型的相等性检查

转载 作者:行者123 更新时间:2023-12-04 07:05:26 26 4
gpt4 key购买 nike

假设我有一个接口(interface):

public interface FooInterface {
public void someMethod();
}

我有一个实现这个接口(interface)的类:
public class FooClass implements FooInterface {
public void someMethod() {
//do cool things
}
public void someOtherMethod() {
//do other cool things
}
}

有没有一种简单的方法可以反射性地找到 FooClass 上映射到 FooInterface 上 someMethod 的方法?

我有类似下面的东西做这个计算,但我很好奇是否有人知道 Java 中的内置系统来做这个计算?我已经制定了以下代码来做到这一点(可能有错误,所以要小心):
public boolean isMethodEquality(Method meth1, Method meth2) {

//Check declaring classes for equality
boolean isAssignable;
isAssignable = meth1.getDeclaringClass().isAssignableFrom(
meth2.getDeclaringClass();
isAssignable |= meth2.getDeclaringClass().isAssignableFrom(
meth1.getDeclaringClass());
if (!isAssignable) {
return false;
}
//check the names for equality
if (!meth1.getName().equals(meth2.getName())) {
return false;
}
//check the parameters for equality
if (meth1.getParameterTypes().length != meth2.getParameterTypes().length) {
return false;
}
for (int i = 0; i < meth1.getParameterTypes().length; i++) {
if (!meth1.getParameterTypes()[i].equals(meth2.getParameterTypes()[i])) {
return false;
}
}
return true;
}

以上应检查签名。有没有另一种内置的方法来做到这一点?

我尝试了.equals,但这没有用,这是有道理的。这些方法是同一方法的不同实现模式(在这种情况下,一个只是没有定义的声明,另一个是定义)。

我也意识到我可以简单地添加一个可继承的注释,但我宁愿避免这种情况,因为它会导致类爆炸。

正如其中一位评论者所指出的,注释仅继承于类。见 java docs更多细节。

我真正在寻找的是方法的“isAssignableFrom”,或者一种轻松比较方法签名的方法。

谢谢。

最佳答案

最简单的(不,它不会表现良好,但在这种情况下你可能不会关心)方法是调用 concreteClass.getMethod() :

Method interfaceMethod = ...; // method whose implementation you're looking for
try {
Method implementationMethod = concreteClass.getMethod(
interfaceMethod.getName(), interfaceMethod.getParameterTypes());
} catch (NoSuchMethodException E) {
// your class may be abstract and thus would not implement given method
} catch (SecurityException E) {
// insufficient permissions
}

关于java - 扩大 Method 类型的相等性检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1174242/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com