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.
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
. Essentially, I need to consider these Methods
equal, but obviously the equals
method indicates they are not equivalent.
Specifically, I need a way to determine if a given Method
obtained through reflection overrides a superclass/interface 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:
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.