2

I need use this method with three distinct classes: Orders, Customers, Suppliers

public void saveObjectKey(String filename, Long start) {
    Query<Orders> query = datastore.createQuery(Orders.class)
            .field("O_ORDERKEY").greaterThan(start);
    for (Orders orders : query.fetch()) {
        Util.writeFile(orders.getPrimaryKey().toString(), filename);
    }
}

I had thought in an ugly solution, a if else if solution:

if(instanceof Orders).... else if(instanceof Customers)..... else if(instanceof Suppliers)....

Now i need a generic solution, how can i do it?

2
  • What is this method supposed to do? And how does it interact with those classes? Commented Jun 17, 2012 at 22:18
  • 8
    You are right, a bunch of instanceof's suggest a bad design. Why not have all three classes implement the same interface, and then call the interface method(s) in this method? Commented Jun 17, 2012 at 22:18

1 Answer 1

4

Can this make sense in your application:

public <T> void saveObjectKey(String filename, Long start, Class<T> clazz, String keyName) {
    Query<T> query = datastore.createQuery(clazz).field(keyName).greaterThan(start);
    for (T o : query.fetch()) {
        Util.writeFile(o.getPrimaryKey().toString(), filename);
    }
}

Then you can use it like:

saveObjectKey(filename, start, Customers.class, customersKeyName);
saveObjectKey(filename, start, Suppliers.class, suppliersKeyName);
saveObjectKey(filename, start, Orders.class, ordersKeyName);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks nobeh, it was im looking for. One more doubt, o.getPrimaryKey() isn't reconized. Some tip for me?
I believe query.fetch() gives you a Collection<SOMETHING> in which SOMETHING has the method getPrimaryKey(). You should cast T o inside the loop to SOMETHING to be able to receive the method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.