jn1kk
jn1kk

Reputation: 5102

Java Generic Parameter Bound In Instantiation

Having a major brain fart right now.

I have this:

public static final Map<WorkType, Class> handler;

Then

handler = new TreeMap<WorkType, Class>() {{
    put(WorkType.SUBMIT, UtilityHandler.class);
}};

Then

JobHandler jobHandler = instantiateHandler(handler.get(work), work, buildingId);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!! this shows a warning unchecked assignment
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Unchecked assignment: 'java.lang.Class' to 'java.lang.Class<? extends JobHandler>

Then

@SuppressWarnings(value="unchecked")
private static JobHandler instantiateHandler(Class<? extends JobHandler> ref, WorkType type, String id) {

    if(ref == null) {
        throw new UnsupportedOperationException("This action is not supposed!");
    }

    try {
        Constructor<JobHandler> constructor = (Constructor<JobHandler>) ref.getConstructor(WorkType.class, String.class);
        JobHandler handler = constructor.newInstance(type, id);
        return handler;
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
        Utilities.writeLogException(null, e);
    }

    return null;

}

I want to get rid of unchecked assignment. I thought I could do this:

public static final Map<WorkType, Class extends JobHandler> handler;

But it is not allowed. Any thoughts/suggestions? Thanks.

Upvotes: 0

Views: 75

Answers (2)

cmbaxter
cmbaxter

Reputation: 35443

I think you want:

Map<WorkType, Class<? extends JobHandler>> handler

Upvotes: 1

sanbhat
sanbhat

Reputation: 17622

I think you should declare

Map<WorkType, Class<? extends JobHandler>> handler

from the code inside the method instantiateHandler it looks like you are expecting a Class object of any subtype of JobHandler and you are trying to instantiate JobHandler object

Upvotes: 1

Related Questions