调用作为参数传递给Java方法的Java类

时间:2022-10-01 21:26:09

I want to write a main method that does some generic setup (opens input and output streams), and then invokes a static method in another class that is passed to it as a run-time argument. How do I achieve this?

我想编写一个main方法来执行一些通用设置(打开输入和输出流),然后在另一个类中调用静态方法,该方法作为运行时参数传递给它。我该如何实现这一目标?

1 个解决方案

#1


1  

I'll assume both the name of the class and the method to call are passed as arguments.

我假设类的名称和要调用的方法都作为参数传递。

You load the class using Class.forName, which will give you a Class instance for it.

您使用Class.forName加载该类,它将为您提供一个Class实例。

You get a Method instance for the method using Class#getMethod, passing in an array of appropriate Class instances to identify the signature, or Class#getMethods and looking through the resulting array.

使用Class#getMethod获取方法的Method实例,传入适当的Class实例数组以标识签名,或者Class#getMethods并查看生成的数组。

You call the method using Method#invoke.

您可以使用Method#invoke调用该方法。

You'll find lots of information about doing this in the Class class documentation and the java.lang.Reflection package documentation.

您将在Class类文档和java.lang.Reflection包文档中找到有关执行此操作的大量信息。

#1


1  

I'll assume both the name of the class and the method to call are passed as arguments.

我假设类的名称和要调用的方法都作为参数传递。

You load the class using Class.forName, which will give you a Class instance for it.

您使用Class.forName加载该类,它将为您提供一个Class实例。

You get a Method instance for the method using Class#getMethod, passing in an array of appropriate Class instances to identify the signature, or Class#getMethods and looking through the resulting array.

使用Class#getMethod获取方法的Method实例,传入适当的Class实例数组以标识签名,或者Class#getMethods并查看生成的数组。

You call the method using Method#invoke.

您可以使用Method#invoke调用该方法。

You'll find lots of information about doing this in the Class class documentation and the java.lang.Reflection package documentation.

您将在Class类文档和java.lang.Reflection包文档中找到有关执行此操作的大量信息。