简体   繁体   English

构造一个在运行时确定类型的对象?

[英]Construct an Object of type determined at runtime?

So I'm trying to test the methods on a certain class (with a default constructor), and the test methods can only be public and of type void , and must start with "test". 因此,我正在尝试在特定类上测试方法(使用默认构造函数),并且测试方法只能是public并且类型为void ,并且必须以“ test”开头。

public static void main(String[] args) throws ClassNotFoundException {
    Class<?> c = null;
    c = Class.forName(args[0]);

    System.out.println(c.getName());
    for (Method m : c.getMethods()) {
        if (m.getName().startsWith("test")
                && m.getReturnType().equals(Void.TYPE)
                && m.getModifiers() == Modifier.PUBLIC) {

            Object o = null;

            try {
                o = c.newInstance();
            } catch (InstantiationException | IllegalAccessException ex) {
                System.out.println(ex.getMessage());
            }

            // ???    
        }
    }
}

So, my checks work, but I do not know how to make a new instance of the class and test the method. 因此,我的检查工作正常,但是我不知道如何制作该类的新实例并测试该方法。 How would I do this? 我该怎么做?

Try with: 尝试:

m.invoke(o);

This will reflectively invoke your method ´m´, given it doesn't receive any arguments. 给定方法“ m”,因为它不接收任何参数,它将反射性地调用它。

One note about checking if the method is public . 关于检查该方法是否public一条说明。 You'd better perform that check this way: 您最好以这种方式执行该检查:

boolean isPublic = Modifier.isPublic(m.getModifiers());

Unless you want to check that the method is only public and has no other modifier, in which case your code is OK. 除非您要检查该方法是公共方法且没有其他修饰符,否则在这种情况下您的代码就可以了。

Exception handling left as an excersice ;) 异常处理作为练习;)

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

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