使用Java中的特定方法创建类

时间:2013-07-26 20:18:52

标签: java class methods parameter-passing

我的代码中有10个特定的方法,我想将它们与类对象一起使用:

void function(){
//do Something that I want
}

class PoseAction{

Pose pose;

void methodDesirable();

PoseAction(Pose ps, Method function()){

  this.pose = ps;
  this.methodDesirable() = function();
}

}

所以当我创建一个新的对象

PoseAction ps = new PoseAction(pose1, action1());

主叫      ps.methodDesirable();

它将调用action1()函数。

可以这样做吗?

提前致谢!

2 个答案:

答案 0 :(得分:0)

函数不是java中的第一类对象。也就是说,您不能直接分配它们或将它们作为方法参数传递。您需要使用对象和接口:

interface Action {
    void fire(Pose pose);
}

class PoseAction {
    Action action;
    Pose pose;

    void methodDesirable() {
        action.fire(pose)
    }

    PoseAction(Pose ps, Action a) {
        pose = ps;
        action = a;
    }
}

并使用它:

PoseAction ps = new PoseAction(pose1, new Action() {
     public void fire(Pose pose) {
          action1(pose);
     }
};
ps.methodDesirable();

答案 1 :(得分:0)

不可能以这种方式,Java不支持delegates。在java中可以使用接口完成:

interface Command {
    void doCommand();
}

PoseAction pa = new PoseAction(new Pose(), new Command() {
    @Override
    public void doCommand() {
        //method body
    }
});

此处new Command() {...}是实现Command接口

的匿名内部类
相关问题