Question

Two methods currently return identical objects, differing only in object name.

Animal getEntity(e) {
    ...
    return Animal
}

Person getEntity(e) {
    ...
    return Person
}

Ideally, I could construct a method which would return a type dynamically, based on how it's called. Does this make any sense?

When I was looking for examples of <T> T, it wasn't clear how I could return a specified type. Elsewhere, a gremlin called "type erasure" seems to be bandied about. Am I barking up the wrong tree? What should I be looking for?

Was it helpful?

Solution

You can not have two methods with the same signature, and the return is not part of the signature.

You could accomplish what you want using an interface as parent of Animal and Person. This will return an appropiate Person or Animal depending on what you pass as arguments. The return type of the method will be the Interface.

public interface Living {}

And:

public class Animal implements Living {}

For person:

public class Person implements Living {}

So your method will be:

public Living getEntity(Something e) {
     // you can return Animal or Person
}

You will need to cast the return of getEntity

Animal myAnimal = (Animal)myClass.getEntity(...);

Another alternative will be to use generics (and you will avoid the casting), and have different instances of the class returning different types. One example (you could follow different strategies):

class Dynamic <T extends Object> {
    T t;

    T getEntity(Object e) {
        return t;
    }

    void setEntity(T e) {
       this.t = e;
    }
}

And to use it:

Dynamic<Animal> animalStore = new Dynamic<>();
Dynamic<Person> personStore = new Dynamic<>();

So animalStore will return an Animal and personStore a Person.

OTHER TIPS

Create a parent class for Animal and Person, maybe called Entity and make that the return type. Abstract all of the common fields and methods into the parent. The only caveat is that you may need to cast to the specific type when the method returns.

Try playing with the Object class, which is the parent class of all objects. Even you have created.

http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top