user2066880
user2066880

Reputation: 5034

Setting return type of method to type of calling object

I have a method defined as follows:

public TYPE getById(ObjectId id) {
    return datastore.get(this.getClass(), id);
}

The method signature of datastore.get() is:

<T, V> T get(Class<T> var1, V var2);

How would I properly set the return type of my method? Note that the object returned by datastore.get() is not the same type as my implementing class, it can be a subclass. Therefore I want the return type to be specific to that class.

Upvotes: 0

Views: 59

Answers (1)

Rudi Angela
Rudi Angela

Reputation: 1473

What I understand is you want something like this:

public class Factory<T> {
  public T getById(ObjectId id) {
    return datastore.get(T, id);
  }
}

public class Class1Factory extends Factory<Class1> {
  public Class1 getById(ObjectId id) {
    return datastore.get(Class1.class, id);
  }
}

You have to use separate Factory classes as you cannot parameterize a class to itself. You cannot say:

public class Class1 extends Parent<Class1> {
  ...
}

Upvotes: 1

Related Questions