简体   繁体   English

我如何运行外部类的所有方法

[英]How can I run all methods of an external class

I have a class "RSTRule", which has several methods and all the methods start with "generate". 我有一个“ RSTRule”类,它具有几种方法,所有方法均以“ generate”开头。 In another class "RSTRules" i want to execute all methods in "RSTRule" with a for loop in it's constructor. 在另一个类“ RSTRules”中,我想在其构造函数中使用for循环执行“ RSTRule”中的所有方法。 I have written the following code but i do not know how do i excute these methods and how do i invoke them,? 我已经编写了以下代码,但是我不知道如何执行这些方法以及如何调用它们?

public class RSTRules extends ArrayList<RSTRule>  {

public RSTRules(){
    Class<?> rstRule = Class.forName("RSTRule");
    Method[] methods = rstRule.getMethods();
        for (Method m : methods) {
           if (m.getName().startsWith("generate")) {
            //Run the method m 
           }
        }

}

also this is a method from the class "RSTRule" 这也是来自“ RSTRule”类的方法

public RSTRule generateBothNotSatisfy_Join(){
        this.discourseRelation=DiscourseRelation.Join;
        this.nucleus=new NucleusSatelliteInRSTRule("Both_Not_Satisfy_User_Desires_in",propNuc);
        this.satellite=new NucleusSatelliteInRSTRule("Both_Not_Satisfy_User_Desires_in",propSat);
        this.ruleName="BothNotSatisfy_Join";
        this.condition=null;
        this.heuristic=10;
        return this;
    }

Class is metaClass in Java (Class describing other class). 类是Java中的metaClass(描述其他类的类)。 So you can't invoke method on it. 因此,您无法在其上调用方法。 To invoke method you need living instance of class you want to invoke methods of. 要调用方法,您需要要调用其方法的类的活动实例。

Here is a little generic example: 这是一个通用的示例:

    Method[] methods = Object.class.getMethods();
    Object o = new Object();
    for (Method method : methods) {
        method.invoke(o, {params for method});
    }

Invoke method takes two parameters. 调用方法需要两个参数。 First is instance on which you want to invoke method, and second are parameters for method. 首先是要在其上调用方法的实例,其次是方法的参数。 (null if method doesn't take any) (如果方法不使用任何方法,则为null)

public RSTRules(){
    Class<?> rstRule = Class.forName("RSTRule");
    Method[] methods = rstRule.getMethods();
        for (Method m : methods) {
           if (m.getName().startsWith(" generate")) {
                method.invoke(rstRule, {params for method}); 
           }
        }

}

For details, please refer to the following link 详情请参考以下链接

http://tutorials.jenkov.com/java-reflection/index.html http://tutorials.jenkov.com/java-reflection/index.html

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

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