如何能够从 getConstructor() 使用 .class? - Java

How to be able to use .class from a getConstructor()? - Java

在 java,我正在为我正在开发的软件开发 API,它将允许人们自行扩展软件。现在,我正在使用一个事件系统,一切正常。我正在尝试使用 .class 来获取所需的参数类型,因此该函数将 运行。有没有我可以用来从构造函数中获取变量的代码(例如具有 class 目录的字符串)然后创建它以便我可以在其上使用 .class ?我很想知道!

注意:如果某些变量或构造函数看起来不像来自 java,可能是因为它们是我正在处理的 API 的一部分。

这是我的代码:

private void throwEvent() {
    PSLPE = new PocketServerListPingEvent(this, Packet.getAddress(), Packet.getPort(), ServerSettings.getPEMOTD());
    ArrayList<Class<?>> Listeners = PluginManager.getListeners();
    for(int i = 0; i < Listeners.size(); i++) {
        Method[] MethodList = Listeners.get(i).getMethods();
        for(int j = 0; j < MethodList.length; j++) {
            if(MethodList[j].isAnnotationPresent(EventHandler.class)) {
                if(MethodList[j].getParameters()[0].getType().equals(PocketServerListPingEvent.class)) {
                    try {
                        Class<?> EventClass = Class.forName(Listeners.get(i).getName());
                        Constructor<?>[] EventCtorList = EventClass.getConstructors();
                        for(int k = 0; k < EventCtorList.length; k++) {
                            Constructor<?> ctor = EventClass.getConstructor(Class.forName(EventClass.getConstructors()[k].getParameters()[0].getType().toString().substring(6)));
                            Object EventObject = ctor.newInstance(EventClass.getConstructors()[k].getParameters()[0].getType());
                            Method EventMethod = EventObject.getClass().getMethod(MethodList[j].getName(), PocketServerListPingEvent.class);
                            EventMethod.invoke(EventObject, PSLPE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

您正在寻找 Class.forName.

它 returns 具有给定名称的 class 的 Class 对象,或者如果没有这样的 class 则抛出异常。例如:

Class<?> chillyDogsClass = Class.forName("net.codeguys.ChillyDogs");

String className = new Scanner(System.in).readLine();
try {
    Class<?> unknownClass = Class.forName(className);
    System.out.println("Successfully found " + unknownClass.toString());
} catch(ClassNotFoundException e) {
    System.out.println(className+" doesn't exist!");
}