Reputation: 2068
Hello i have the follow two methods
first
public ObjectId getObjectIdByRegionName(Region region) {
Query<Region> query = datastore.createQuery(Region.class);
query.field("R_NAME").equal(region.getName());
return query.get().getId();
}
second
public ObjectId getObjectIdByNationName(Nation nation) {
Query<Nation> query = datastore.createQuery(Nation.class);
query.field("N_NAME").equal(nation.getName());
return query.get().getId();
}
how could i turn them into generic method?
Upvotes: 0
Views: 100
Reputation: 424983
Although duffymo's approach is preferable (cleaner etc), if you don't have control over the source for your parameter classes (or you can't impose interfaces etc), you could just do this:
public <T> ObjectId getObjectIdByNationName(T param, String name, String fieldName) {
Query<T> query = datastore.createQuery((Class<T>)param.getClass());
query.field(fieldName).equal(name);
return query.get().getId();
}
or even this non-generic version (since you can do without type scoping):
public ObjectId getObjectIdByNationName(Object param, String name, String fieldName) {
Query<?> query = datastore.createQuery(param.getClass());
query.field(fieldName).equal(name);
return query.get().getId();
}
It would however mean some duplication by the caller to call with the field name and the name every time. If each parameter type is only called from one location, there would be no duplication.
Upvotes: 2
Reputation: 308743
Try this:
public <T> ObjectId getObjectByName(T name)
Or add them to an interface or class that uses generics:
public interface LocationDao<T extends Nameable> {
ObjectId findByName(T location);
}
So now you'll need something like this:
public interface Nameable {
String getName();
}
As noted in the comments, you need to have a parameter that has a getName()
method. You'll need a restriction to make that true.
Upvotes: 2