简体   繁体   English

从不同的类动态调用方法

[英]Dynamically invoke a method from a varying class

I have a requirement where in i need to invoke method from class in a particular pattern which is obtained as input argument. 我有一个需要在哪里我需要从类中调用作为输入参数的特定模式的方法。

   public RandomMethod(String ClassName){
        //Eg For Class Name Abc , there is a method AbcProcessor which i need to invoke
        ClassName.ClassNameProcessor    
        }

Since i am getting the argument as String , i am not able to figure out how to cast String into a form where i can call something like Abc.AbcProcessor() 由于我将参数设为String,因此我无法弄清楚如何将String转换为可以调用类似Abc.AbcProcessor()的形式

I believe there is some way to do this using reflections. 我相信有一些方法可以通过反射来实现。 But i am not sure how to proceed. 但是我不确定如何进行。

You need to use reflecton, indeed : 您确实需要使用reflecton

public void randomMethod(String fullyQualifiedClassName, String methodName) throws ReflectiveOperationException {
    Class<?> clazz = Class.forName(fullyQualifiedClassName);

    clazz.getMethod(methodName).invoke(null);
}

which would work assuming you are calling public static method with no arguments 假设您正在调用不带参数的公共静态方法,它将起作用

By reflection you can do that, try following sample: 通过反思,您可以尝试以下示例:

Class A: A类:

public class A {
    public void print(){
        System.out.println("A");
    }
}

Class B: B类:

public class B {
    public void print(){
        System.out.println("B");
    }    
}

Invoking print() from A and B: 从A和B调用print()

public class Test {

    public static void callPrint(String className){
        try {
            Class clazz = Class.forName(className);
            Object obj = clazz.newInstance();
            clazz.getDeclaredMethod("print").invoke(obj);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        callPrint("test.A");
        callPrint("test.B");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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