Java动态函数创建 [英] Dynamic Function Creation in Java

查看:595
本文介绍了Java动态函数创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图找出是否存在某种方法可以动态地将方法创建/分配给Java中的类.如果是C,我将使用指针按照以下步骤进行操作:

So I'm trying to figure out if there is some method to dynamically create/assign a method to a class in Java. If it were C, I would just do it as follows using pointers:

public class Foo {  

  void bar(void *ptr) {....}  

};  

int main() {  
  Foo f = new Foo();  
  f.bar({"my function" ...})  
}  

但是,Java当然没有指针,所以有什么办法可以从Java应用程序中获得类似的功能?

However, Java of course has no pointers, so is there any way to get a similar functionality out of a Java application?

推荐答案

在Java中,通常会声明一个带有要调用的方法的接口.例如,如果您的函数只想执行一些代码,则可以声明一个Runnable并实现其run方法.

In Java, you would normally declare an interface with a method to be called. For example, if your function simply wants to execute some code, you would declare a Runnable and implement its run method.

public class Foo {
    void bar(Runnable function) {
       for(int i = 0; i < 5; i++) {
           function.run();
       }
    }

    static void myFunction() {
         System.out.println("my Function!");
    }

    public static void main(String[] ignored) {
         Foo f = new Foo();
         f.bar( new Runnable() { public void run() {
             myFunction();
         }});
    }

}

这篇关于Java动态函数创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆