【问题标题】:Call a class from another class without having to change the class type (or the return) Java从另一个类调用一个类而无需更改类类型(或返回)Java
【发布时间】:2017-03-08 23:33:09
【问题描述】:

我正在尝试从另一个班级运行一个班级。但是当我将类名存储在数组中时,它要求我更改类型。我希望用户输入一个数字,该数字将被输入数组并以该数组值运行该类。 到目前为止,这是我的代码:

public class All_Challenges {

public static void main(String[] args) {
    System.out.println("Which class do you want to run?: ");
    System.out.println("1. The first class");

Class[] theFiles = new Class[31];
    theFiles[1] = Challenge_1_Whats_Your_Name.main(args);
    theFiles[1].main(args);
    }
}

最后两行给了我一个错误,因为它们让我将类类型从void 更改为类型class,然后添加return statement。我有大约 30 个这样的方法,所以我不想在所有其他类中更改我的主要方法。我应该写什么东西,这样我就不必这样做了。我认为这与我的数组是什么“类型”有关。或者可能与main.(args); 行有关 奇怪的是,当我不从数组中调用它时,它不会要求我更改类型。

【问题讨论】:

  • 不清楚你想要达到什么目的 - 你为什么要创建一个数组?你希望用它做什么?
  • JVM 通常会代表您而不是您直接调用main() 方法。你能告诉我们你想在这里完成什么吗?
  • 您正在分配一个void,这是将main(args) 调用到Class 类型对象的变量(无论它是什么)实例或任何其他变量的结果,你不能因为void 不能设置为值。您需要做的是(可能)将类存储在该数组中,并使用reflection 对其进行实例化并调用某个方法。除非你更清楚地说明你想做什么。
  • 您不能直接在代表该类的Class 对象上调用该类的静态方法。如果 Class 是您感兴趣的类的唯一句柄,那么您必须使用反射来调用其静态方法。
  • 或者只使用Interface

标签: java arrays class main


【解决方案1】:

问题是您试图将方法放入类数组中。

    Class[] theFiles = new Class[31];
    theFiles[1] = Challenge_1_Whats_Your_Name.class;
    try {
        theFiles[1].getMethod("main", String[].class).invoke(args);
    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        e.printStackTrace();
    }

这应该适合你

【讨论】:

  • 这不会在这个类中运行Challenge_1_Whats_Your_Name 程序。
【解决方案2】:

您可以使用反射来做到这一点:

public class TestMain {

    private static final Class<?>[] classArray = {A.class, B.class};

    public static void main(String[] args) {
        for (Class<?> classExec : classArray) {
            try {
                //get main
                Method method = classExec.getMethod("main", String[].class);
                method.invoke(null, (Object) args);
            } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    public static class A {
        public static void main(String[] args) {
            System.out.println("A");
        }
    }

    public static class B {
        public static void main(String[] args) {
            System.out.println("B");
        }
    }   

}

参考:https://stackoverflow.com/a/4980149/1255493

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 2015-03-11
    • 2016-10-12
    • 2018-11-27
    相关资源
    最近更新 更多