Problem using model.getClass().getMethod in case of inheritance

前端 未结 2 1184
夕颜
夕颜 2021-01-21 22:19

I\'m following this article on Oracle Network to implement MVC when developing desktop applications. I have a problem, though: I\'m using an abstract Directory class ex

2条回答
  •  庸人自扰
    2021-01-21 22:50

    package com.test;
    
    import java.lang.reflect.Method;
    
    public class Test {
        public static void main(String[] args) throws Exception {
        Test test = new Test();
        Child child = new Child();
    
        // Your approach, which doesn't work
        try {
            Method method = test.getClass().getMethod("doSomething", new Class[] { child.getClass().getSuperclass() });
            method.invoke(test, child);
            System.out.println("This works");
        } catch (NoSuchMethodException ex) {
            System.out.println("This doesn't work");
        }
    
        // A working approach
        for (Method method : test.getClass().getMethods()) {
            if ("doSomething".equals(method.getName())) {
            if (method.getParameterTypes()[0].isAssignableFrom(child.getClass())) {
                method.invoke(test, child);
                System.out.println("This works");
            }
            }
        }
    
        }
    
        public void doSomething(Parent parent) {
    
        }
    }
    
    class Parent {
    
    }
    
    class Child extends Parent {
    
    }
    

    You need add .getSuperclass() to child

提交回复
热议问题