tags:

views:

168

answers:

3

I have a method that takes a list of entities (Classes) and does some computation. To describe my needs here is the simplest outline of the method (pseudo-code):

public void do(List<Class<?> entities) {
    for (Class<?> entity : entities) {
     List<?> list = session.createCriteria(entity).list();
     for (Object o : list) {
      System.out.println(o.getClass().getSimpleName() + " " + o.getId());
     }
    }
}

Is there a way that I can access/get the Id of o?

A: 

Not unless you have the property named the same on all entities, then you could use reflection to call the getter for that property. If they are all named something different, then you would get a NoSuchMethodException

Mike Pone
I can guarantee that it has getId() method and I take the risk of getting an `Exception`.
nimcap
+1  A: 

Well, maybe it'll get many critics but all your entity classes may implement this interface:

public interface EntityWithId {
    Integer getId();
    void setId(Integer id);
}

If your id's are not integers may be the interface could be:

public interface EntityWithId<T> {
    T getId();
    setId(T id);
}

public class Entity implements EntityWithId<String> {
    private String id;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    .
    .
    .
}

Anyway, I don't see why you'd want to get the IDs of all your entities, it's a strange solution for a strange requirement, hehe.

victor hugo
I've done almost exactly that before now, but stopped as I found alternative ways to do what I needed. I do generally have all my mapped entity classes implement an empty marker interface, though.
araqnid
+6  A: 
session.getIdentifier(o)
araqnid