java 实现排队,如何在Java中排队和调用实际方法(而不是立即评估)?

There are a list of tasks that are time sensitive (but "time" in this case is arbitrary to what another program tells me - it's more like "ticks" rather than time). However, I do NOT want said methods to evaluate immediately. I want one to execute after the other finished. I'm using a linked list for my queue, but I'm not really sure how/if I can access the actual methods in a class without evaluating them immediate.

The code would look something like...

LinkedList l = new LinkedList();

l.add( this.move(4) );

l.add( this.read() );

l.removeFirst().call();

//wait 80 ticks

l.removeFirst().call();

move(4) would execute immediately, then 80 ticks later, I would remove it from the list and call this.read() which would then be executed.

I'm assuming this has to do with the reflection classes, and I've poked around a bit, but I can't seem to get anything to work, or do what I want. If only I could use pointers...

To clarify: These commands will be called by another class that does not know anything about the timing, which is why this class has to handle it. It will simply call methods that are expected to be executed in sequence. Some of the methods do not return anything but change state.

解决方案

You can certainly do something just like your example. You could do something using interfaces and classes and forgo reflection, too. I don't know what would work best for your situation. Here's how you can do it with reflection.

Check out the Class class and the Method class.

// Get the Class of the type you're grabbing methods from

Object target = new SomeObject();

Class theClass = target.getClass();

// Or, use the class literal:

Class theClass = SomeObject.class;

// Get the methods you want

// You need to know the method name and its parameter types.

Method aMethod = theClass.getMethod("move", Integer.class);

List myMethods = new LinkedList();

myMethods.add(aMethod);

// Later, you need an object on which to invoke a method.

Method currentMethod = myMethods.get(0);

currentMethod.invoke(target, 4);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值