如何在Java中排队和调用实际方法(而不是立即评估)? [英] How to queue and call actual methods (rather than immediately eval) in java?

查看:201
本文介绍了如何在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.

代码看起来像...

LinkedList<Method> l = new LinkedList<Method>();
l.add( this.move(4) );
l.add( this.read() );
l.removeFirst().call();
//wait 80 ticks
l.removeFirst().call();

move(4)将立即执行,然后在80个滴答之后,我将其从列表中删除并调用this.read(),然后将其执行.

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.

查看 Class 类和 Method 类. /p>

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<Method> myMethods = new LinkedList<Method>();
myMethods.add(aMethod);

// Later, you need an object on which to invoke a method.
Method currentMethod = myMethods.get(0);
currentMethod.invoke(target, 4);

这篇关于如何在Java中排队和调用实际方法(而不是立即评估)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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