Prince of Sweden
Prince of Sweden

Reputation: 475

How to use Polymorphism, Generics in method signatures?

I have a case where I am trying to use polymorphism and method signatures plus casting.

I have an interface like so:

<T extends ParentClass> convert(Class<T> clazz, ParameterType type)

Where I want to return a child (don't know which type) and in the method I accept another unknown class and a type which is simply an enum. The goal is to take in an object, convert it to another and then hand it back.

I am having issues with my usage and specifically with trying to make tests for this. Here is the implementation:

@Override
public <T extends ParentClass> T convert(Class<T> clazz, ParameterType type)

    //Check if clazz is an instance of a specific object and use that specific converter
    if(clazz.isInstance(AnObject.class)) {
        AbObjectConverter anObjectConverter = new anObjectConverter;
        anObjectConverter.convert(castClass(clazz, AnObject.class);
    }

The goal is to have more than AnObject to convert, so I can send in any object there. Then check which one it is and call the appropriate converter. The class I want to convert is a class (one of many) which share the same parent, hence the class <T> in the method.

CastClass simply does this:

private static<T> T castClass(Object o, Class<T> clazz) {
    return clazz.isInstance(o) ? clazz.cast(o) : null;
}

I'm trying to make unit tests for this, but how do I do this without errors? I want to make an object that I want to convert, send it to my method and test functionality. For example:

@Test
public void testConvertingShouldSucceed() {
    ObjectToConvert object = new ObjectToConvert();
    object.setname("Hello");

    service.convert(object, ApplicationType.CONVERT)
}

But this does not work, as I can't cast my object to convert to T or whatever, so it complains on the object

How do I actually make use of this to make it compile and work? It feels like it should be simple to use parents, generics and such to send it types I won't know until runtime. Maybe I'm making it needlessly complex.

Upvotes: 1

Views: 90

Answers (1)

Appana Sairao
Appana Sairao

Reputation: 36

Your method signatures are not correct.

for castClass function, the first parameter you defined is Object, but while calling this function you are passing a Class instance.

Also the main convert function is taking only Class instance in the method definition, where as you are passing Object to it in the test case.

Upvotes: 1

Related Questions