Java中如何将方法作为参数传递呢?
下文笔者讲述将方法作为参数传递的方法及示例分享,如下所示
方法作为参数传递的实现思路:
只需定义相应的接口
然后将方法中的参数类型设置为接口
运行接口中的方法,即可将方法作为参数传递的效果
例:
public class CommandExample
{
public interface Command
{
public void execute(Object data);
}
public class PrintCommand implements Command
{
public void execute(Object data)
{
System.out.println(data.toString());
}
}
public static void callCommand(Command command, Object data)
{
command.execute(data);
}
public static void main(String... args)
{
callCommand(new PrintCommand(), "hello world");
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


