クラスを取得し、その主な機能を呼び出す方法

レヴィの:

私は、クラスと文字列の配列を取得する方法を記述し、指定された配列を持つクラスのmainメソッドを呼び出したいです。

このようなもの:

    public static void ExecuteMain(DefaultClass cls, String[] args){
        cls.main(args);
    }

問題は、私はいくつかのクラスでそれをやりたい、で、タイプとして正確なクラスを渡すことはできません。私もそれは同じクラス名を持つ私のクラスメートのためのテスターとして使用する必要がありますので、他のクラスのすべてがデフォルトのインタフェースやクラスを実装することはできません。

それらの制限でそれを行う方法はありますか?

アービンド・クマールのAvinash:

下記のおメソッドを定義する方法です。

public static void executeMain(Class<?> cls, Object[] args) {
    try {
        Object[] param = { args };
        Method method = cls.getDeclaredMethod("main", args.getClass());
        method.invoke(cls, param);
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        e.printStackTrace();
    }
}

デモ

Assignment1.java:

import java.util.Arrays;

public class Assignment1 {
    public static void main(String[] args) {
        if (args == null) {
            System.out.println("Welcome to Assignment1");
        } else {
            System.out.println("Arguments to main in Assignment1: " + Arrays.toString(args));
        }
    }
}

Assignment2.java

import java.util.Arrays;

public class Assignment2 {
    public static void main(String[] args) {
        if (args == null) {
            System.out.println("Welcome to Assignment2");
        } else {
            System.out.println("Arguments to main in Assignment2: " + Arrays.toString(args));
        }
    }
}

テストクラス:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) {
        Assignment1.main(null);
        Assignment1.main(new String[] { "Hello", "World" });
        Assignment2.main(null);
        Assignment2.main(new String[] { "Hello", "World" });
        executeMain(Assignment1.class, new String[] { "Good", "Morning" });
        executeMain(Assignment2.class, new String[] { "Good", "Morning" });
    }

    public static void executeMain(Class<?> cls, Object[] args) {
        try {
            Object[] param = { args };
            Method method = cls.getDeclaredMethod("main", args.getClass());
            method.invoke(cls, param);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

出力:

Welcome to Assignment1
Arguments to main in Assignment1: [Hello, World]
Welcome to Assignment2
Arguments to main in Assignment2: [Hello, World]
Arguments to main in Assignment1: [Good, Morning]
Arguments to main in Assignment2: [Good, Morning]

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=371014&siteId=1