java method 创建,Java动态函数创建

在Java中,可以通过声明接口并实现其方法来达到类似C语言中使用指针动态调用函数的效果。例如,创建一个Runnable接口,然后在类中定义一个接受Runnable参数的方法。在main方法中,可以创建匿名内部类来实现Runnable接口,并调用目标方法。这样可以在运行时动态地指定要执行的代码块。
摘要由CSDN通过智能技术生成

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" ...})

}

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

解决方案

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();

}});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值