[英]Checking a superclass/interface method and an overridden method for equality
I've run into a situation where I have a Method
instance from an interface definition and a Method
instance of the same method from an implementing class. 我碰到一个情况我有一个
Method
实例从一个接口定义和Method
相同的方法,从实现的类的实例。
For example: 例如:
public interface Foo {
void bar();
}
public class FooImpl implements Foo {
public void bar() {
System.out.println("foobar");
}
}
Using reflection, I have obtained a Method
instance of bar
from the Foo
interface and its derived implementation from FooImpl
. 使用反射,我从
Foo
接口获得了bar
的Method
实例,并从FooImpl
获得了它的实现。 Essentially, I need to consider these Methods
equal, but obviously the equals
method indicates they are not equivalent. 从本质上讲,我需要考虑这些
Methods
相等,但是很明显, equals
方法表明它们并不等效。
Specifically, I need a way to determine if a given Method
obtained through reflection overrides a superclass/interface Method
. 具体来说,我需要一种方法来确定通过反射获得的给定
Method
是否覆盖超类/接口Method
。
I'm currently using a workaround which avoids the situation completely by finding the "least-derived" method from a given class, but I'm wondering if there's a more elegant solution. 我目前正在使用一种变通方法,通过从给定类中找到“最少派生”方法来完全避免这种情况,但是我想知道是否有更优雅的解决方案。
I haven't taken the modifiers into consideration in the equals method but this should get you reasonably close if you want to use this algorithm: 我没有在equals方法中考虑修饰符,但是如果您想使用以下算法,这应该可以让您相当接近:
package test;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class TestFooBar {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
try {
// Get the class of interest
Class fooImpl = Class.forName("test.FooImpl");
// Test all the methods
for(Method m : fooImpl.getMethods()) {
boolean overriden = false;
List<Class> parents = new ArrayList<Class>();
for(Class c : fooImpl.getInterfaces()) {
parents.add(c);
}
if(fooImpl.getSuperclass() != null) parents.add(fooImpl.getSuperclass());
for(Class c : fooImpl.getInterfaces()) {
for(Method sm : c.getMethods()) {
if(equals(sm, m)) {
overriden = true;
break;
}
}
if(overriden) break;
}
System.out.println(m+": "+(overriden ? "Overriden" : "Not overriden"));
}
}
catch(Exception e) {
e.printStackTrace();
}
}
private static boolean equals(Method m1, Method m2) {
if(!m1.getName().equals(m2.getName())) return false;
String t1 = "";
for(Class c : m1.getParameterTypes()) {
t1+=c.getName()+"/";
}
String t2 = "";
for(Class c : m2.getParameterTypes()) {
t2+=c.getName()+"/";
}
if(!t1.equals(t2)) return false;
return true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.