Master Noob
Master Noob

Reputation: 715

Matching A parameter and return type using generics

Can the return type be be matched to the parameter type using generics?

Example case:

I have an abstract class that will be implemented to import data from different POJO's, this class contains an abstrcact method importData.

The returned Object from importData must be of the same type as the Object passed to the method.

public abstract POJO importData(final POJO dataObject, final String messageId);

as the Object type is different for each implementation of the abstract method and the type does not extend another, how can the abstract method be defined so that the implementations return type and passed type MUST match?

Edit:

Tried and tested:

public abstract <T> T importData(final T jaxbObject, final String messageId);

Result:

The return type of the method does not have to match the passed objects type.

Upvotes: 2

Views: 300

Answers (2)

Leviand
Leviand

Reputation: 2805

You have to assign a letter for your class type, that will be assigned when your method is used, based on the type you use when the method is called

public abstract T importData(final T dataObject, final String messageId);

You can then, in your implementation, checking the type of your object for different behaviours

YourAbstractClass c = new YourAbstractClass() {
            @Override
            public <T> T importData(T dataObject, String messageId) {
                if(dataObject instanceof String){
                    //doSomething
                }else if (dataObject instanceof POJO){
                    //do POJO things
                }
                return null;
            }
        };

Upvotes: 2

Lino
Lino

Reputation: 19926

You can use a method level generic parameter:

public abstract <T> T importData(final T dataObject, final String messageId);

Beware though that this type T may vary for every call made. E.g following are possible:

POJO myPojo = myClass.importData(otherPojo, "messageId");
Integer someInt = myClass.importData(5, "otherMessageId");
String aSring = myClass.importData("Hello World", "anotherMessageId");

If that is not what you want, you may use the suggestion of a class level generic parameter by @Leviand.

Upvotes: 2

Related Questions