akash doijode
akash doijode

Reputation: 13

How to queue methods in java

How can I add methods and its parameters to a queue in Java? For example:

class Demo {
    int add(int x, int y) {
        return x*y;
     }
    // Add this method
}

If we have to queue this method with parameters, how can we accomplish this?

i.e

queueObject.add(this.add(10,20));
queueObject.add(this.add(20,30));

queueObject.remove();
queueObject.remove();

Upvotes: 1

Views: 2444

Answers (3)

Philippe Simo
Philippe Simo

Reputation: 1459

You can use reflection this way:

public class Catalog {
  public void print(Integer x, Integer y){      
    System.out.println(x*y);
  }

}

public static void main(String[] args) {
    Catalog cat = new Catalog();
    Queue<Method> queueObject = new LinkedList<Method>();
    try {
        Method printMethod = cat.getClass().getDeclaredMethod("print", new Class[]{Integer.class,Integer.class});       

        //Now you can add and remove your methods from queues
        queueObject.add(printMethod);

        //invoke the just added method
        System.out.println(queueObject.element().invoke(cat,10,20));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}`

i get this output: 200

Upvotes: -1

Barath
Barath

Reputation: 5283

Using Java8:

        @Test
        public void test(){

            QueueMethod q1= ()->System.out.println("q1 hello");
            QueueMethod q2= ()->System.out.println("q2 hello");
            Queue<QueueMethod> queues=new  LinkedList<QueueMethod>();
            queues.add(q1);
            queues.add(q2);     
            queues.forEach(q->q.invoke());      
        }

        @FunctionalInterface
        interface QueueMethod{      
            void invoke();
        }


 Output: 

q1 hello
q2 hello

Upvotes: 0

marstran
marstran

Reputation: 27971

If you are using Java 8, you can create a queue of IntSupplier like this:

Queue<IntSupplier> queue = // some new queue
queue.add(() -> add(10, 20));
queue.add(() -> add(20, 30));

// The getAsInt-method calls the supplier and gets its value.
int result1 = queue.remove().getAsInt();
int result2 = queue.remove().getAsInt();

Upvotes: 5

Related Questions