java匿名类作为参数与新方法

时间:2017-05-31 08:08:24

标签: java anonymous-class

当我通过反射搜索方法时,它显示了新提供的方法。但我不知道如何调用该方法,如果有人知道该怎么做,请告诉我。

//some pakage
pakage xyz;

class A {
    // a simple method of class A
    public void aMethod() {
        //simple print statement
        System.out.println("A class method");
    }
}

class B {
    // a method of class B that takes A types as an argument
    public void bMethod(A arg) {
        Class c = Class.forName("xyz.A");

        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
        }
    }
}

class Test {
    public static void main(String[] args) {
        B bObj = new B();
        bObj.bMethod(new A() {
            public void anotherMethod() {
                System.out.println("another method");
            }
        });
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用反射来调用特定对象上的方法:

public void invokeSomeMethodOnA(A arg, String methodName) {
    Method method = arg.getClass().getDeclaredMethod(methodName);

    //To invoke the method:
    method.invoke(arg, parameters here);
}

答案 1 :(得分:0)

我想也许这就是你想要的。

package xyz;

import java.lang.reflect.Method;

class A {
    // a simple method of class A
    public void aMethod() {
        //simple print statement
        System.out.println("A class method");
    }
}

class B {
    // a method of class B that takes A types as an argument
    public void bMethod(A arg) throws Exception {
        Class c = Class.forName(arg.getClass().getName());

        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
            method.invoke(arg);
        }
    }
}

class Test {
    public static void main(String[] args) throws Exception {
        B bObj = new B();
        bObj.bMethod(new A() {
            public void anotherMethod() {
                System.out.println("another method");
            }
        });
    }
}