简体   繁体   中英

Can I use Reflection to call a method's super method?

I want to call a method's super method using reflection, but my method doesn't work, and I'm not sure it's possible. Here's my method to call the super method for the equals(Object) method of class T, which is also called the targetClass here:

private ToBooleanThrowingBiFunction<T> getSuperEquals() {
  Class<T> targetClass = getTargetClass();
  Class<?> superClass = targetClass.getSuperclass();
  while ((superClass != Object.class) && (superClass != null)) {
    try {
      Method method = superClass.getDeclaredMethod("equals", Object.class);
      return (thisOne, thatOne) -> {
        try {
          return (Boolean) method.invoke(thisOne, thatOne);
        } catch (InvocationTargetException e) {
          throw new IllegalStateException(e.getCause());
        }
      };
    } catch (NoSuchMethodException e) {
      superClass = superClass.getSuperclass();
    }
  }
  throw new IllegalArgumentException(String.format("E10: No superclass of %s has an equals() method.", targetClass));
}

@FunctionalInterface
private interface ToBooleanThrowingBiFunction<T>  {
  boolean eval(T thisOne, T thatOne) throws IllegalAccessException;
}

This code correctly extracts a Method that holds the super.equals() method. But when I call it, it executes the equals() method of the targetClass . Is there a way to do this?

After trying several things, I've concluded that this just isn't possible. (This doesn't surprise me, but I thought I'd give it a shot. I'm often surprised by what you can do through reflection, but you can't do this.)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM